如何通知JUnit在@DataPoints注释方法中生成的异常?

Tho*_*asH 5 java junit unit-testing junit4

我已经使用JUnit的实验注释为hashCodeequals方法实现了通用测试@Theory.测试用例类本身基于dfa的版本.

但是,当我尝试测试java.net.InetAddress该类时,如果提供数据点的方法包含抛出异常的代码(在本例中为an UnknownHostException),我遇到了一个特殊的问题:

所以我尝试了两种方法,这两种方法都导致了同样令人不满意的结果:

  1. 将方法声明为抛出适当的异常:

    @DataPoints
    public static InetAddress[] declareException() throws UnknownHostException {
        return new InetAddress[] {
            InetAddress.getByName("not a valid internet address")
        };
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 显式捕获异常并重新抛出AssertionError:

    @DataPoints
    public static InetAddress[] rethrowAsAssertionError() {
        try {
            return new InetAddress[] {
                InetAddress.getByName("not a valid internet address")
            };
        } catch(UnknownHostException ex) {
            throw new AssertionError(ex);
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

在这两种情况下,AssertionError都会抛出一条无用的消息"从未找到满足方法假设的参数.违反假设:[]",这与首先没有带@DataPoints注释的方法相同.

有没有人知道是否有办法将异常传播给JUnit(最终是用户)或者这是JUnit中的错误?

Mat*_*ell 8

这是一个已知问题137:DataPoints方法中隐藏的异常.

解决方法是在@BeforeClass中创建数据点,然后从DataPoints中使用它:

private static InetAddress[] datapoints;

@BeforeClass
public static void generateData() throws UnknownHostException {
  // do all the work of generating the datapoints
  datapoints = new InetAddress[] {
    InetAddress.getByName("not a valid internet address")
  };
}

@DataPoints
public static InetAddress[] data() {
  return datapoints;
}
Run Code Online (Sandbox Code Playgroud)

这应该工作.

有一个待处理的拉取请求328:@DataPoints相关的修复,但它目前仍在讨论中,尚未被接受.