Reputation: 37
My method returns null sometimes and not null values so how to write a assert for those scenarios
example:assertNotNull(some statement)
Upvotes: 0
Views: 130
Reputation: 140613
Simple:
@Test
public void testFooGivesNotNull() {
assertNotNull(foo.bar(somethingLeadingToNotNull));
}
@Test
public void testFooGivesNull() {
assertNull(foo.bar(somethingElseLeadingToNull));
}
In other words: you do that by identifying the possible test cases, to then write at least one test for each of the possible paths.
And for the record: returning null is rarely a good idea. That null is the first step towards running into a NullPointerException. Consider alternatives, such as
Optional
Upvotes: 8
Reputation: 6330
A good way to use Assert.assertNotNull is via static import.
import static org.junit.Assert.assertNotNull;
assertNotNull(yourValueTobeCheckAsNull, "This should not be null");
Upvotes: 1
Reputation: 2486
Just call your function and add an error message:
Assert.assertNotNull(someFunction(), "This should not be null");
Upvotes: 1