Ashley Ashley - 7 months ago 37
Java Question

Expecting custom exception instead of null pointer exception while junit testing

I have method in java class :

@Context
UriInfo uriInfo;
public void processRequest(@QueryParam ("userId") @DefaultValue("") String userId)
{
String baseURI = uriInfo.getBaseUri().toString();
if(userId == null)
{
//UserIdNotFoundException is my custom exception which extends Exceptition
throw new UserIdNotFoundException();
}
}


When I'm junit testing the above method expecting for UserIdNotFoundException when userId parameter is Null, I get the following Assertion error :
expected an instance of UserIdNotFoundException but <java.lang.NullPointerException> is java.lang.NullPointerException
.

@Test
public void testProcessRequest_throws_UserIdNotFoundException()
{
expectedException.expect(UserIdNotFoundException.class);
processRequest(null);
}


My custom exception class :

public class UserIdNotFoundException extends Exception
{

public UserIdNotFoundException()
{

}

public UserIdNotFoundException(String message)
{
super(message);
}
}

Answer

I prefer the annotation:

@Test(expected = UserIdNotFoundException.class)
public void testProcessRequest_throws_UserIdNotFoundException() {
     processRequest(null);
}

The problem might be that your processRequest implementation might be hitting the NPE before you have a chance to check for user id.

This is a good thing: Your test shows that the implementation does not meet your requirement. You can fix it forever now.

This is what TDD is good for.

Comments