I am running this code, and realized that getAllParameters()
method runs twice for some reason. Because the static field enumMap
is initialized outside that method, it gets populated twice, which results in duplicate elements and fails the test I'm running.
I figured that initializing enumMap
inside the method fixes the problem, as the map does get reset when the method runs the 2nd time.
Even though this fixes the problem, I am wondering why this happens when running Maven Test? I played around with the number of parameters, thinking that might possibly affect how many times the method runs, but it only seems to be running twice.
@RunWith(Parameterized.class)
public class MyTest {
private static Map<String, List<Class<? extends LocalizedJsonEnum>>> enumMap = new HashMap<>();
@Parameter
@SuppressWarnings({"WeakerAccess", "unused"})
public Class<? extends LocalizedJsonEnum> currentEnum;
@Parameter(value = 1)
@SuppressWarnings({"WeakerAccess", "unused"})
public String currentClassName;
/**
* Generate a list of all the errors to run our test against.
*
* @return the list
*/
@Parameters(name = "{1}.class")
public static Collection<Object[]> getAllParameters() throws Exception {
Collection<Object[]> parameters = new LinkedList<>();
Reflections reflections = new Reflections("com.class.path");
Set<Class<? extends LocalizedJsonEnum>> JsonEnums = reflections.getSubTypesOf(LocalizedJsonEnum.class);
//workaround: initialize here
//enumMap = new HashMap<>();
//some code that inserts elements into the enumMap and parameters
return parameters;
}
@Test
public void testEnumIdentifierIsNotDuplicated() throws Exception {
String enumId;
if (currentEnum.isAnnotationPresent(Identifier.class)) {
enumId = currentEnum.getAnnotation(Identifier.class).value();
} else {
enumId = currentEnum.getSimpleName();
}
List<Class<? extends LocalizedJsonEnum>> enumList = enumMap.get(enumId);
if (enumList.size() > 1) {
StringBuilder sb = new StringBuilder("Enum or identifier [" + enumId + "] has been duplicated in the following classes:\n");
for (int listIndex = 0; listIndex < enumList.size(); listIndex++) {
Class<? extends LocalizedJsonEnum> enumDuplicate = enumList.get(listIndex);
sb.append(" [").append(listIndex).append("] Enum Class:[").append(enumDuplicate.getName()).append("]\n");
}
fail(sb.toString());
}
}