This commit is related to BAEL-7342 ()

This commit aims to add a test class "CheckIfStringBuilderContainsCharUnitTest" that suggests several ways to check if a StringBuilder has a char or not.
This commit is contained in:
MohamedHelmyKassab 2023-12-21 06:58:07 +02:00 committed by GitHub
parent 22c187747e
commit a87d4fbdb3
1 changed files with 44 additions and 0 deletions
core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/stringbuilderhaschar

View File

@ -0,0 +1,44 @@
package com.baeldung.stringbuilderhaschar;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class CheckIfStringBuilderContainsCharUnitTest {
StringBuilder stringBuilder = new StringBuilder("Welcome to Baeldung Java Tutorial!");
char targetChar = 'o';
@Test
public void givenStringBuilder_whenUsingIndexOfMethod_thenCheckIfSCharExists() {
int index = stringBuilder.indexOf(String.valueOf(targetChar));
assertTrue(index != -1);
}
@Test
public void givenStringBuilder_whenUsingContainsMethod_thenCheckIfSCharExists() {
boolean containsChar = stringBuilder.toString().contains(String.valueOf(targetChar));
assertTrue(containsChar);
}
@Test
public void givenStringBuilder_whenUsingJavaStream_thenCheckIfSCharExists() {
boolean charFound = stringBuilder.chars().anyMatch(c -> c == targetChar);
assertTrue(charFound);
}
@Test
public void givenStringBuilder_whenUsingIterations_thenCheckIfSCharExists() {
boolean charFound = false;
for (int i = 0; i < stringBuilder.length(); i++) {
if (stringBuilder.charAt(i) == targetChar) {
charFound = true;
break;
}
}
assertTrue(charFound);
}
}