简体   繁体   中英

Exception when using an enum member in parameterized test class with JUnit

I have a parameterized test class with an enum member as parameter.

public enum MyEnum {
    A,
    B
}

This is the significant part of the test class:

@ParameterizedRobolectricTestRunner.Parameters
public static Collection<Object[]> data() {
    return Arrays.asList(new Object[][] {
            {MyEnum.A}
    });
}

public MyTestClass(MyEnum value) {
}

When running the tests, I get this exception:

java.lang.IllegalArgumentException: argument type mismatch

If I change the constructor to

public MyTestClass(Object value) {
    MyEnum x = (MyEnum)value;
}

I get this exception:

java.lang.ClassCastException: com.test.MyEnum cannot be cast to com.test.MyEnum

Can anybody tell me whats going on there? Especially the second case seems totally strange. I'm mainly a C# developer, so maybe this is special case in Java? If I use other data types like Integer it works fine.

Thanks for helping!

Edit: The enum has actually 8 members, I just changed it here. Also, the constructor has more than one parameter, I just simplified the example. The type of value is correctly com.test.MyEnum

Edit2: The ParameterizedRobolectricTestRunner is the problem. If I use the (standard) Parameterized TestRunner, everything works fine. In this special case it is ok, since I don't test UI. But when testing UI, the problem would still occur.

That Class cast exception is quite strange. However, the following code ran for me:

@RunWith(Parameterized.class)
public class ParamTest {

  MyEnum expected;

  public enum MyEnum{A,B}

  // Each parameter should be placed as an argument here
  // Every time runner triggers, it will pass the arguments
  public ParamTest(MyEnum expected) {
    this.expected = expected;
  }

  @Parameterized.Parameters
  public static Collection<Object[]> data() {
    return Arrays.asList(new Object[][] {
        { MyEnum.A },
        { MyEnum.B },
    });
  }

  // This test will run 2 times
  @Test
  public void myTest() {
    System.out.println("Enum is : " + expected);
    assertEquals(expected, expected);
  }
}

It prints:

Enum is : A
Enum is : B

You can also do it like below. It's a little bit cleaner.

@RunWith(Parameterized.class)
public class ParamTest {

  public enum MyEnum{A,B}

  @Parameterized.Parameter public MyEnum expected;

  @Parameterized.Parameters
  public static MyEnum[] data() {
    return MyEnum.values();
  }

  @Test
  public void myTest() {
    System.out.println("Enum is : " + expected);
    assertEquals(expected, expected);
  }
}

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