我正在运行此代码,并意识到getAllParameters()
方法由于某种原因运行了两次。因为静态字段enumMap
在该方法之外被初始化,所以它会被填充两次,这会导致重复的元素并且无法运行我的测试。
我认为在方法中初始化enumMap
可以解决问题,因为当方法第二次运行时,地图会重置。
即使这解决了问题,我想知道为什么在运行Maven Test时会发生这种情况?我玩了很多参数,认为这可能会影响方法运行的次数,但它似乎只运行了两次。
@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());
}
}