power_settings_new

how to assert a null pointer exception

by (262 points)
+1 vote
123 views
Passing an invalid data throwing "NPE", which is expected. But how to assert those exception.Please provide me some example.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.

1 Answer

by (171 points)
0 votes

There are two ways you can do this.

1.) By directly asserting the object is null.

e.g.

String str = null;
Assert.assertTrue(str == null, "String str is not null");
 
Or you can try using try catch block to catch NPE and assert it or log it.
 
try{
str.toLowerCase();
}catch(NullPointerException nullPointerException){
System.out.print("Null pointer exception");
//you can do your assertion here
}
 
Hope that helps!
by (262 points)
a method returning NPF and i am assertiing it.

ex :
class A{
testmethod()
{
return null;
}
}

Test Class B {
test()
{
assert (testmethod);
}
by (171 points)
Assert has to have two values right? Or there should be a boolean value. You can try something like below.

Assert.assertTrue(testmethod(),null);

Hope that helps!
by (262 points)
@Test(expectedExceptions=NullPointerException.class)
{
.....
}

I am trying this , correct me if i am wrong
by (171 points)
This looks good, but how do you see the future of this code? Tomorrow if you are asked to log or implement custom report is that possible to do so by using above code?
add
...