I’ve written a generic class to help us write our unit tests easier. It’s basically to allow us to use the same methods to get our tests setup, and have some common methods to test with. I know that the point of a generic class is to not care about what class we are working with, but having this information is helpful (the concrete implementations can then have an instance variable that is of the proper type).
Here is my class:
public abstract class AbstractModuleTest<M extends Module> {
@Autowired protected WebDriver driver;
private final Type type;
protected AbstractModuleTest() {
final ParameterizedType parameterizedType =
(ParameterizedType) getClass().getGenericSuperclass();
type = parameterizedType.getActualTypeArguments()[0];
}
protected <S extends AbstractPage> 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);
}
Is there an easier way to get the Class I’m dealing with (to avoid the StringUtils.substringAfter call)?
You don’t need
Classin that method. Whenm.getClass().equals(type))returnstrueit’s safe to do unchecked cast (perhaps there can be some corner cases ifMis generic, but your code doesn’t catch them too):