【发布时间】:2017-04-29 09:12:22
【问题描述】:
我正在为我的 java 应用程序编写一个集成测试框架,但遇到了一个我无法解决的问题。请让我解释一下:
以下代码 sn-ps 是简化的类,以提高可见性:
我得到了以下抽象类:
public abstract class AbstractTestModel<T extends AbstractTestModel> {
public T doSomething(){
return getThis();
}
public T getThis(){
return (T) this;
}
public <U extends AbstractTestModel<T>> U as(Class<U> type){
AbstractTestModel<T> obj = this;
if (obj.getClass().isAssignableFrom(type)){
return type.cast(obj);
}else{
throw new AssertionError("This (" + obj.getClass().getName() +")could not be resolved to the expected class " + type.getName());
}
}
}
并且可能有像这样的具体类:
public class ConcreteTestModel1 extends AbstractTestModel<ConcreteTestModel1> {
public void doSomethingElse(){
}
}
我还写了一个工厂类。该工厂从服务器下载 JSON 对象并实例化其中一个具体类 - 取决于 JSON 响应。这个具体的类有许多用于测试 JSON 响应的辅助方法。问题是,工厂方法总是返回一个“AbstractTestModel”。
集成测试如下所示(简化):
public class SomeTest {
TestModelFactory testModelFactory;
@Before
public void init(){
testModelFactory = new TestModelFactory();
}
@Test
public void someTest(){
AbstractTestModel anyModel = testModelFactory.createModel("someIdOfTheServer");
//ERROR: this does not work! Cannot resolve method doSomethingElse():
anyModel.doSomething().as(ConcreteTestModel1.class).doSomethingElse();
//as() method returns AbstractTestModel instead of ConcreteTestModel1
//this works:
AbstractTestModel as = anyModel.as(ConcreteTestModel1.class);
//this does not work:
ConcreteTestModel1 asConcreteTestModel1 = anyModel.as(ConcreteTestModel1.class);
}
}
方法 as(Class type) 应该检查给定的类是否有效,将“this”转换为所需的类并返回它,但它总是返回 AbstractTestModel。
如果我将“as”方法设为静态,或者如果我像这样摆脱泛型类...
public abstract class AbstractTestModel {
/*
Not possible to return the superclass anymore
public T doSomething(){
return getThis();
}
public T getThis(){
return (T) this;
}
*/
public <U extends AbstractTestModel> U as(Class<U> type){
AbstractTestModel obj = this;
if (obj.getClass().isAssignableFrom(type)){
return type.cast(obj);
}else{
throw new AssertionError("This (" + obj.getClass().getName() +")could not be resolved to the expected class " + type.getName());
}
}
}
...然后它工作正常,但我当然不能再以所有其他方法返回具体类。
感谢您阅读这篇长文。 你知道我在这里做错了什么吗?有解决办法吗?
感谢您的任何提示,祝您有美好的一天!
曼努埃尔
【问题讨论】:
-
顺便说一句:将“as”方法设为静态会导致单元测试代码非常难看,因为最后,我需要能够编写用户可读的单元测试。另一个信息:工厂使用反射来确定具体类。
-
是的。使用原始类型会删除该类的所有泛型。
标签: java unit-testing generics casting integration-testing