我正在尝试为我的单元测试用例创建一个可重用的模板类。假设类 Sample 和 SampleTest 属于同一个包,而 Template 属于不同的包。实例化 Sample 类时出错。我希望该方法将被执行,就好像它是可以访问 SampleTest 类的方法一样。有没有办法使这项工作?
public SampleTest extends Template<Sample> {
public void testMethod() {
getTarget().method();
}
}
public class Template<T> extends TestCase {
/** Spied, object instance to test. */
private transient T targetObject;
/** Test class type to be derived as parameter type of test subclass. */
private transient final Class<T> targetType;
@Override
public void setUp() throws Exception
{
super.setUp();
setupTargetObject();
}
protected void setupTargetObject()
{
final T realObject = targetType.newInstance(); //ERROR here if class under test is non-public
targetObject = Mockito.spy(realObject);
}
protected Template() {
final ParameterizedType paramedType = (ParameterizedType) getClass().getGenericSuperclass();
targetType = (Class<T>) paramedType.getActualTypeArguments()[0];
}
protected T getTarget()
{
return targetObject;
}
}