我编写了一门通用类,帮助我们更轻松地编写单元测试。它基本上允许我们使用相同的方法来获得我们的测试设置,并且有一些常用的测试方法。我知道泛型类的关键在于不关心我们正在使用的是哪个类,但拥有这些信息是有帮助的(具体实现可以具有适当类型的实例变量)。
这是我的班级:
public abstract class AbstractModuleTest {
@Autowired protected WebDriver driver;
private final Type type;
protected AbstractModuleTest() {
final ParameterizedType parameterizedType =
(ParameterizedType) getClass().getGenericSuperclass();
type = parameterizedType.getActualTypeArguments()[0];
}
protected M setup(final S s, final String errorMsg) {
for (final Module m : s.getModules()) {
if (m.getClass().equals(type)) {
try {
final Class c = Class.forName(StringUtils.subStringAfter(type.toString(), " "));
return (M) c.cast(m);
} catch (ClassNotFoundException cnfe) { throw new RuntimeException(cnfe); }
}
}
Assert.fail(errorMsg);
}有没有更容易的方法来获得我正在处理的类(以避免StringUtils.substringAfter调用)?