java - 单元测试架构问题

标签 java unit-testing junit

所以我开始为以下代码安排单元测试:

public interface MyInterface {
  void MyInterfaceMethod1();
  void MyInterfaceMethod2();
}

public class MyImplementation1 implements MyInterface {
  void MyInterfaceMethod1() {
    // do something
  }

  void MyInterfaceMethod2() {
    // do something else
  }

  void SubRoutineP() {
    // other functionality specific to this implementation
  }
}

public class MyImplementation2 implements MyInterface {
  void MyInterfaceMethod1() {
    // do a 3rd thing
  }

  void MyInterfaceMethod2() {
    // do something completely different
  }

  void SubRoutineQ() {
    // other functionality specific to this implementation
  }
}

有多个实现,并期待更多的实现。

我最初的想法是用这样的东西来节省自己重写单元测试的时间:

public abstract class MyInterfaceTester {
  protected MyInterface m_object;  

  @Setup
  public void setUp() {
    m_object = getTestedImplementation();
  }

  public abstract MyInterface getTestedImplementation();

  @Test
  public void testMyInterfaceMethod1() {
    // use m_object to run tests
  }

  @Test
  public void testMyInterfaceMethod2() {
    // use m_object to run tests
  }
}

然后我可以轻松地对其进行子类化以测试特定于实现的附加方法,如下所示:

public class MyImplementation1Tester extends MyInterfaceTester {
  public MyInterface getTestedImplementation() {
    return new MyImplementation1();
  }

  @Test
  public void testSubRoutineP() {
    // use m_object to run tests
  }
}

从实现 2 开始也是如此。

所以我的问题是:有什么理由不这样做吗? JUnit 似乎很喜欢它,它满足了我的需求,但我在阅读的任何单元测试书籍和示例中都没有真正看到过类似的内容。

我是否无意中违反了一些最佳实践?我是否正在为自己的心痛做好准备?有没有我没有考虑过的更好的方法?

感谢您的帮助。

最佳答案

is there any reason not to do this?

没有。做吧。测试是正是这个原因的类。

I haven't really seen anything like it in any of the unit testing books and examples I've been reading.

继续阅读。简介不包括这一点。

Is there some best practice I'm unwittingly violating?

没有。

Am I setting myself up for heartache down the road?

没有。

有些人对“脆弱性测试”感到紧张。您可以在这里找到一些问题,寻找实现它的方法,这样对软件的更改不会同时导致测试发生变化。从长远来看,试图创建“健壮”的测试是愚蠢的。您希望编写测试,以便软件的可见界面级别的每个小更改都需要测试重写。

您需要测试,以便不可见的内部更改不需要测试重写。

类和子类的使用与这些考虑是正交的。

Is there simply a much better way out there I haven't considered?

没有。面向对象的重点。正是出于这个原因,测试是一个类。

关于java - 单元测试架构问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2999480/

相关文章:

java - $NON-NLS-1$ 是什么意思?

java - 更改 Checkbox for Android 的选中和未选中图标

unit-testing - 对于不编写单元测试有什么好的理由吗?

java - 带有 SpringRunner.class 的 JUnit @Category 注释

java - 私有(private)变量的返回值

java - 使用apache POI在word文件生成中保留换行符

c# - (什么时候)使用 FluentAssertions 是个好主意?

php - 如何在不测试 protected 方法时达到 100% 的代码覆盖率

java - 使用 JUnitPerf 测试问题

selenium - 在实践中使用 Selenium 2.0 WebDriver