I've searched on google and clicked link after link on many different sites and none of the available answers helped me. This is unfortunate since some of the sites reference the same answer, which I wasn't able to make fit my problem. That link was (Junit testing for a boolean method)...
The output from trying to run the test is: "method testAddObject() should be void." The actual method is a boolean method and if I set the test up as void, I get a different error. I can't just arbitrarily make it void.
I'll use code snippets. First my code, and then my jUnit test.
Code:
public boolean add(Object ob) {
boolean isSuccessful = true;
/**
* if array is full, get new array of double size,
* and copy items from old array to new array
*/
if (isFull())
{
expandArray();
}
else if (!isFull())
{
// add new item; update numItems
items[numItems] = ob;
numItems++;
}
else
isSuccessful = false;
return isSuccessful;
} // end add
JUNIT TEST:
@Test
public boolean testAddObject() {
boolean result = true;
boolean ans;
AList arraylist = new AList(3);
arraylist.add("apple");
arraylist.add("pear");
ans = arraylist.add("melon");
return ans == result;
}
void assertTrue(boolean condition)Checks that a condition is true.
In this example, we have learned that how we can JUnit Test Void Method. We have also learned that how to catch the exception if it is thrown by a void method. Actually testing mechanism is same for all methods, but void methods are special as we don't have any returning value to be matched for testing.
All JUnit test methods should be void. It's in the test assertions that confirms if your code is producing the intended output. For your scenario, the assertTrue
method will check if the output of your method returns true
.
There are other types of assertions such as assertEquals
and assertFalse
. For more information of the different types of assertions, check the documentation.
So you can modify your test case like this
@Test
public void testAddObject() {
boolean ans;
AList arraylist = new AList(3);
arraylist.add("apple");
arraylist.add("pear");
ans = arraylist.add("melon");
assertTrue(ans);
}
where assertTrue
checks that ans is a boolean with a value of true
JUnit methods can't have a return type, so you test for success with the following:
@Test
public void testAddObject() {
//Your data setup and invocation of the add method
assertTrue(ans == result);
}
There are tons of assertion options if you want more than True/False, they can be found here: http://junit.sourceforge.net/javadoc/org/junit/Assert.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With