带有JUnit的继承



我有两个从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()}
        );
    }
}

我将TestClassA类重命名为MyController,因为听起来MyController是测试系统的一部分。有了这个,你可以用你的B和C类来测试它,比如:

public class HelloContTest {
    @Test
    public void testSomethingWithB() throws Exception {
        MyController controller = new MyController();
        controller.setTheClass(new B());
        controller.doSomething();
    }
    @Test
    public void testSomethingWithC() throws Exception {
        MyController controller = new MyController();
        controller.setTheClass(new C());
        controller.doSomething();
    }
}

相关内容

  • 没有找到相关文章

最新更新