Exception when using enumeration member in parameterized test class using JUnit

I have a parameterized test class with an enumeration parameter as a parameter.

public enum MyEnum { A, B } 

This is a 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 tests, I get this exception:

 java.lang.IllegalArgumentException: argument type mismatch 

If I changed 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 someone tell me what is going on there? Especially the second case seems completely strange. I'm mainly a C # developer, so maybe this is a special case in Java? If I use other data types like Integer, it works fine.

Thanks for the help!

Edit: The listing is actually 8 members, I just changed it here. In addition, the constructor has more than one parameter, I just simplified the example. Value type is correct com.test.MyEnum

Edit2: ParameterizedRobolectricTestRunner problem. If I use the (standard) Parameterized TestRunner, everything works fine. In this special case, this is normal since I am not testing the user interface. But when testing the user interface, the problem will still occur.

+7
java junit robolectric
source share
2 answers

This exceptional class class is rather strange. However, for me there was the following code:

 @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); } } 

He prints:

Enum is: a
Enum: b

+1
source share

You can also do this as shown below. It is a little 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); } } 
0
source share

All Articles