AssertNull should be used or AssertNotNull

2019-03-09 15:17发布

问题:

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.

回答1:

Use assertNotNull(obj). assert means must be.



回答2:

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


回答3:

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



标签: java junit