Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 249
ThomasH Avatar asked Nov 17 '11 11:11

ThomasH


1 Answers

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.

like image 97
Matthew Farwell Avatar answered Nov 14 '22 21:11

Matthew Farwell