Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AssertNull should be used or AssertNotNull

Tags:

java

junit

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.

like image 358
Bohn Avatar asked Aug 19 '11 15:08

Bohn


People also ask

What is assertNull in JUnit?

Assertions. assertNull() checks that object is null. In case, object is not null, it will through AssertError. public static void assertNull(Object actual) public static void assertNull(Object actual, String message)

What is the difference between assertEquals and assertSame?

The explanation is here – assertEquals() uses equals() method to validate if the two objects are equal whereas assertSame() uses the operator == to validate if two objects are equal. Both of these approaches vary; hence the results are different as well.

Why do we use assertTrue?

assertTrue is used to verify if a given Boolean condition is true. This assertion returns true if the specified condition passes, if not, then an assertion error is thrown.

What does assert NOT null do?

NotNull(Object, String)Verifies that the object that is passed in is not equal to null If the object is null then an AssertionException is thrown.


2 Answers

Use assertNotNull(obj). assert means must be.

like image 164
Petar Minchev Avatar answered Sep 20 '22 10:09

Petar Minchev


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); 
like image 27
punya Avatar answered Sep 20 '22 10:09

punya