Added test code for counting words in a string in Java

This commit is contained in:
alfred.samanga@gmail.com 2019-08-14 20:39:00 +02:00
parent c23cf58cd8
commit 0dcf126861
3 changed files with 25 additions and 14 deletions

View File

@ -1,3 +0,0 @@
This file exists to ensure this empty directory is committed in Git.
Please remove this file when this directory is populated.

View File

@ -2,19 +2,9 @@ package com.baeldung.string.wordcount;
import java.util.StringTokenizer;
/**
* Created by alfred on 14 August 2019
*/
public class WordCounter {
public static void main(String[] args) {
//test string
String random = "Lorem%Ipsum is-simply dummy text.";
System.out.printf("Using delimiter, word count: %d\n", countWordsUsingTokenizer(random));
System.out.printf("Using no library method, word count: %d\n", countWordsManually(random));
System.out.printf("Using punctuation regex, word count: %d\n", countWordsUsingRegex(random));
System.out.printf("\n\n%s\n\n", random);
}
public static int countWordsUsingRegex(String arg) {

View File

@ -0,0 +1,24 @@
package com.baeldung.string.wordcount;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class WordCountUnitTest {
private String string1 = "This is a test sentence with eight words";
private String string2 = "This#is%a test sentence with eight words";
@Test
public void givenStringWith8Words_whenUsingRegexCount_ThenResultEqual8() {
assertThat(WordCounter.countWordsUsingRegex(string2) == 8).isTrue();
}
@Test
public void givenStringWith8Words_whenUsingManualMethod_ThenWordCountEqual8() {
assertThat(WordCounter.countWordsManually(string1) == 8).isTrue();
}
@Test
public void givenAStringWith8Words_whenUsingTokenizer_ThenWordCountEqual8() {
assertThat(WordCounter.countWordsUsingTokenizer(string1) == 8).isTrue();
}
}