prasanna
prasanna

Reputation: 37

Assert statement for junit

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

Answers (3)

GhostCat
GhostCat

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

  • returning a special object that represents "null"
  • returning an Optional
  • throwing an exception

Upvotes: 8

nagendra547
nagendra547

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

Tobias Geiselmann
Tobias Geiselmann

Reputation: 2486

Just call your function and add an error message:

Assert.assertNotNull(someFunction(), "This should not be null");

Upvotes: 1

Related Questions