AssertNull should be used or AssertNotNull

JavaJunit

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

Use assertNotNull(obj). assert means must be.

Solution 2 - Java

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);

Solution 3 - Java

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

Solution 4 - Java

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBohnView Question on Stackoverflow
Solution 1 - JavaPetar MinchevView Answer on Stackoverflow
Solution 2 - JavapunyaView Answer on Stackoverflow
Solution 3 - JavahvgotcodesView Answer on Stackoverflow
Solution 4 - JavaVladiView Answer on Stackoverflow