Skip to content

Commit 0733075

Browse files
alxkmalxkm
and
alxkm
authored
test: CountCharTest (#5423)
test: CountCharTest Co-authored-by: alxkm <[email protected]>
1 parent b2815db commit 0733075

File tree

2 files changed

+20
-9
lines changed

2 files changed

+20
-9
lines changed

src/main/java/com/thealgorithms/others/CountChar.java

+7-4
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,16 @@ private CountChar() {
55
}
66

77
/**
8-
* Count non space character in string
8+
* Counts the number of non-whitespace characters in the given string.
99
*
10-
* @param str String to count the characters
11-
* @return number of character in the specified string
10+
* @param str the input string to count the characters in
11+
* @return the number of non-whitespace characters in the specified string;
12+
* returns 0 if the input string is null
1213
*/
13-
1414
public static int countCharacters(String str) {
15+
if (str == null) {
16+
return 0;
17+
}
1518
return str.replaceAll("\\s", "").length();
1619
}
1720
}

src/test/java/com/thealgorithms/others/CountCharTest.java

+13-5
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,23 @@
22

33
import static org.junit.jupiter.api.Assertions.assertEquals;
44

5+
import org.junit.jupiter.api.DisplayName;
56
import org.junit.jupiter.api.Test;
7+
import org.junit.jupiter.params.ParameterizedTest;
8+
import org.junit.jupiter.params.provider.CsvSource;
69

710
class CountCharTest {
811

9-
@Test
10-
void testCountCharacters() {
11-
String input = "12345";
12-
int expectedValue = 5;
12+
@ParameterizedTest(name = "\"{0}\" should have {1} non-whitespace characters")
13+
@CsvSource({"'', 0", "' ', 0", "'a', 1", "'abc', 3", "'a b c', 3", "' a b c ', 3", "'\tabc\n', 3", "' a b\tc ', 3", "' 12345 ', 5", "'Hello, World!', 12"})
14+
@DisplayName("Test countCharacters with various inputs")
15+
void testCountCharacters(String input, int expected) {
16+
assertEquals(expected, CountChar.countCharacters(input));
17+
}
1318

14-
assertEquals(expectedValue, CountChar.countCharacters(input));
19+
@Test
20+
@DisplayName("Test countCharacters with null input")
21+
void testCountCharactersNullInput() {
22+
assertEquals(0, CountChar.countCharacters(null));
1523
}
1624
}

0 commit comments

Comments
 (0)