我在java类有方法:期待自定义异常,而不是空指针异常而JUnit的测试
@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();
}
}
当我的JUnit测试上面的方法为预期时UserIdNotFoundException userid参数是空的,我得到以下声明错误: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);
}
我的自定义异常类:
public class UserIdNotFoundException extends Exception
{
public UserIdNotFoundException()
{
}
public UserIdNotFoundException(String message)
{
super(message);
}
}
我的执行如何在检查之前触发空指针异常。我不调用userId上的任何字符串方法。或者我没有明白你的观点。此外,我将userId作为来自Url的查询参数。唯一的可能是它可能涉及一些空的检查。 – Ashley
您必须发布processRequest的实现以供我为您拼写。一个更好,更教育的想法可能是在调试器中逐步完成该过程。在processRequest的第一行放置一个断点,看看观察到的行为与您的期望不符。 – duffymo
我按照你的建议进行了调试。该错误显示在行uriInfo.getBaseUri()。toString()它似乎。因此,我把这条线后if检查。测试现在显示绿色栏。但我仍然没有得到理由。 – Ashley