Reputation: 149
I have a few methods in my class
public class StringChecking
{
public static void main(String[] args);
public void stringChecker(String text, int number); //takes a string and prints that out.
}
I want to write Unit test to test the 'stringChecker()
' method. I was wondering how I would go about doing that. When I create an object of type StringChecking
in my JUnit Testing class, I can't seem to access stringChecker()
method from that instance.
StringChecker method prints out certain number of words of the text passed in depending on the parameter.I wish to check to see if the first 10 words getting printed out are same as the expected results.
JUnit test class
String expected = "My name is";
asserEquals(expected, actual);
I'm guessing I will have make my stringChecker method return something, inorder to do the check. But I don't understand why I can't access the method from testing class.
Upvotes: 0
Views: 16718
Reputation: 106390
If you're attempting to assert values coming back, then your method signature is incorrect - it should be returning a String
. From there, you can perform the usual operation with JUnit (your main
method serves no purpose in this context):
@Test
public void checkString() {
String expected = "My name is";
int actual = 3; // assuming words in string
StringChecking testObj = new StringChecking();
assertEquals(expected, testObj.stringChecker(expected + " Bob", 3);
}
Merely printing out values asserts/validates nothing - they provide visual confirmation, which can be often incorrect or invalid.
Java has to know what those values are, and the most direct way to do that is to return the value you need back.
This isn't to say that you can never test a void
method, but that in this case, it's not appropriate.
Upvotes: 4
Reputation: 262474
The code would be easier to test if instead of printing the numbers, the method returned them to the caller.
If you want to test the actual printing, you could set a spy object to System.out that instead of printing collects the data. Then your test can assert the correctness of that output.
Upvotes: 7