在 junit 测试时期望自定义异常而不是空指针异常



我在java类中有方法:

@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();
     }
 }
当我在用户 Id

参数为 Null 时测试上述期望用户 IdNotFoundException 的方法时,我收到以下断言错误: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);
     }
}

我更喜欢注释:

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

问题可能是您的processRequest实现可能在您有机会检查用户 ID 之前命中 NPE。

这是一件好事:您的测试表明实现不符合您的要求。 您现在可以永久修复它。

这就是TDD的好处。

您必须编写自定义异常类,此示例可能会对您有所帮助。

示例代码:

class UserIdNotFoundException extends Exception{  
 UserIdNotFoundException  (String s){  
  super(s);  
 }  
}  

测试异常:

 public void processRequest(String userId)
{
     if(userId == null)
     {
         //UserIdNotFoundException is my custom exception which extends Exception
         throw new UserIdNotFoundException("SOME MESSAGE");
     }
 } 

从异常类中删除默认构造函数,JVM 为您隐式创建它/

您可能没有使用值设置uriInfo,并且正在对 null 值调用方法。您确定您的测试设置为为uriInfo提供值吗?或者getBaseUri()可能会返回null,并调用toString()可能会抛出NullPointerException。这将通过在调试器中检查getBaseUri()的返回值来完成。

通常,您可以使用带有 bean 的配置来运行测试,也可以添加 setter 来设置测试类中的值以模拟它或在测试中给出一个值。这应该有助于避免NullPointerException

无论哪种方式,您都应该在方法中执行任何实际工作之前始终执行失败验证。

最新更新