简体   繁体   中英

How to notify JUnit of exceptions generated in @DataPoints annotated methods?

I have implemented a generic test for the hashCode and equals methods using JUnit's experimental @Theory annotation. The test case class itself is based on dfa's version .

However, when I was trying to test the java.net.InetAddress class, I have come across a peculiar problem if the method that supplies the data points contains code that throws an exception (in this case an UnknownHostException ):

So I tried two alternatives that both led to the same unsatisfactory result:

  1. Declare the method as throwing the appropriate exception:

     @DataPoints public static InetAddress[] declareException() throws UnknownHostException { return new InetAddress[] { InetAddress.getByName("not a valid internet address") }; } 
  2. Explicitly catch the exception and re-throw as an AssertionError :

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

In both cases, an AssertionError is thrown with the unhelpful message "Never found parameters that satisfied method assumptions. Violated assumptions: []" , which is the same as not having a @DataPoints annotated method in the first place.

Does anyone know if there is a way to propagate the exception to JUnit (and, ultimately, the user) or is this a bug in JUnit?

This is a known problem 137: Exceptions hidden in DataPoints methods .

The workaround is to create your data points in a @BeforeClass, and then just use it from the 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;
}

and this should work.

There is a pending pull request 328: @DataPoints-related fixes , but it's currently still under discussion, it has not yet been accepted.

It is a known issue alright. However, I found an easier solution. just rename data method. Do not return primitive variables from DataPoints. For confirmation, I am attaching my screenshot.

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM