From 0733075498ee41f4d750d64e2168c635c528ee5b Mon Sep 17 00:00:00 2001 From: Alex Klymenko Date: Wed, 28 Aug 2024 18:45:23 +0200 Subject: [PATCH] test: `CountCharTest` (#5423) test: CountCharTest Co-authored-by: alxkm --- .../com/thealgorithms/others/CountChar.java | 11 +++++++---- .../thealgorithms/others/CountCharTest.java | 18 +++++++++++++----- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/thealgorithms/others/CountChar.java b/src/main/java/com/thealgorithms/others/CountChar.java index ad8581377..00cff6860 100644 --- a/src/main/java/com/thealgorithms/others/CountChar.java +++ b/src/main/java/com/thealgorithms/others/CountChar.java @@ -5,13 +5,16 @@ public final class CountChar { } /** - * Count non space character in string + * Counts the number of non-whitespace characters in the given string. * - * @param str String to count the characters - * @return number of character in the specified string + * @param str the input string to count the characters in + * @return the number of non-whitespace characters in the specified string; + * returns 0 if the input string is null */ - public static int countCharacters(String str) { + if (str == null) { + return 0; + } return str.replaceAll("\\s", "").length(); } } diff --git a/src/test/java/com/thealgorithms/others/CountCharTest.java b/src/test/java/com/thealgorithms/others/CountCharTest.java index 382ba4246..2b87d3806 100644 --- a/src/test/java/com/thealgorithms/others/CountCharTest.java +++ b/src/test/java/com/thealgorithms/others/CountCharTest.java @@ -2,15 +2,23 @@ package com.thealgorithms.others; import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; class CountCharTest { - @Test - void testCountCharacters() { - String input = "12345"; - int expectedValue = 5; + @ParameterizedTest(name = "\"{0}\" should have {1} non-whitespace characters") + @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"}) + @DisplayName("Test countCharacters with various inputs") + void testCountCharacters(String input, int expected) { + assertEquals(expected, CountChar.countCharacters(input)); + } - assertEquals(expectedValue, CountChar.countCharacters(input)); + @Test + @DisplayName("Test countCharacters with null input") + void testCountCharactersNullInput() { + assertEquals(0, CountChar.countCharacters(null)); } }