java - 使用 JUnit 进行继承

标签 java mockito junit4

我有两个从 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/

相关文章:

java - Mockito 模拟列表时出现问题

java - 编写 JUnit 测试用例时使用 SpringRunner 而不使用 SpringContext 是一个好习惯吗?

java - Jcr查询多个具有abs路径的节点

java - 将 JPanel 添加到 BorderLayout.Center 时,以前的内容仍然可见

java - Mockito:验证模拟(带有 "RETURNS_DEEP_STUBS")返回比预期更多的调用

java - Mysql 8.0 的 Hibernate 配置

spring - @Rollback 在 Spring+Hibernate+Junit 测试中不起作用

Java Spring : Content type 'multipart/form-data;boundary ;charset=UTF-8' not supported

java - Android 将 ArrayList<Object> 保存为 SharedPreference

java - 将模拟对象添加到 Mockito spy 列表 <>