JUnit 的继承

Inheritance with 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 class 重命名为 MyController,因为听起来 MyController 是被测系统的一部分。有了它,您可以像这样用 B 和 C classes 测试它:

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();
    }
}