我有两个从 A 扩展而来的类(B 和 C)。
我正在尝试以一种可以传递 B 和 C 的具体实现并让它们运行的方式编写单元测试。例如:
abstract class A {
abstract doSomething();
public static void send(A a){
// sends a off
}
}
class B extends A {
public void doSomething(){
this.send(this)
}
class C extends A {
public void doSomething(){
this.send(this);
this.write(this)
}
public void write(A a){
//writes A to file
}
}
现在,我正在寻找一种抽象地对其进行单元测试的方法,并且只需传递实现并让单元测试运行。例如:
//setup junit testsuite info
class TestClassA {
private A theClass;
public void testDoSomething(){
this.theClass.doSomething();
}
}
// would like to be able to do
class Runner {
B b = new B();
C c = new C();
// run TestClassA with b (I know this doesnt work, but this is what I'd like to do)
TestClassA.theClass = b;
TestClassA.run();
// run TestClassA with c (I know this doesnt work, but this is what I'd like to do)
TestClassA.theClass = c;
TestClassA.run();
}
有人对如何实现这一目标有任何想法吗?
最佳答案
@RunWith(Parameterized.class)
public class ATest {
private A theClass;
public ATest(A theClass) {
this.theClass= theClass;
}
@Test
public final void doSomething() {
// make assertions on theClass.doSomething(theClass)
}
@Parameterized.Parameters
public static Collection<Object[]> instancesToTest() {
return Arrays.asList(
new Object[]{new B()},
new Object[]{new C()}
);
}
}
关于java - 使用 JUnit 进行继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28511068/