Bohn
Bohn

Reputation: 26919

AssertNull should be used or AssertNotNull

This is a pretty dumb question but my first time with unit testing so: lets say I have an object variable like obj and I want my unit test to Fail if this obj is Null. so for assertions, should I say AssertNull or AssertNotNull ? I get confused how they are named.

Upvotes: 90

Views: 388221

Answers (5)

Fred Danna
Fred Danna

Reputation: 172

In JUnit 4, IDEA (UE 2020) suggests using assertThat(..., notNullValue()); instead of Assert.assertNotNull(...).

For instance:

  1. IDEA warning
  2. IDEA suggestions
  3. IDEA fix

Upvotes: 0

punya
punya

Reputation: 301

The assertNotNull() method means "a passed parameter must not be null": if it is null then the test case fails.
The assertNull() method means "a passed parameter must be null": if it is not null then the test case fails.

String str1 = null;
String str2 = "hello";              

// Success.
assertNotNull(str2);

// Fail.
assertNotNull(str1);

// Success.
assertNull(str1);

// Fail.
assertNull(str2);

Upvotes: 29

Vladi
Vladi

Reputation: 1990

I just want to add that if you want to write special text if It null than you make it like that

  Assert.assertNotNull("The object you enter return null", str1)

Upvotes: 5

Petar Minchev
Petar Minchev

Reputation: 47383

Use assertNotNull(obj). assert means must be.

Upvotes: 176

hvgotcodes
hvgotcodes

Reputation: 120258

assertNotNull asserts that the object is not null. If it is null the test fails, so you want that.

Upvotes: 7

Related Questions