繁体   English   中英

关于单元测试依赖

[英]About unit-test dependency

我正在尝试为我目前正在从事的项目编写一些基本的单元测试,我的服务有一个方法addPlaneModel来添加平面 model (在引擎盖下它将PlaneModel实例添加到TreeMap并抛出自定义如果TreeMap已经包含键则异常)。

我可以编写一个测试(例如shouldAddNewPlane_Succeed )来查看它是否正确添加了PlaneModel但是如果我想创建一个测试来查看PlaneModel已经存在(例如shouldAddNewPlane_ThrowExistingModelException因为我应该调用addPlaneModel两次以使其抛出例外,但如果shouldAddNewPlane_Succeed测试没有首先运行,我真的不知道该方法是否可以正常工作。

我读过单元测试应该彼此独立,但我无法真正掌握在这种情况下如何做到这一点,我是否必须按顺序运行它们?

如果要在运行测试之前执行一些常用代码,可以使用 JUnit 中的@Before方法注解。 例如:

@Before
public void init() {
    LOG.info("startup");
    list = new ArrayList<>(Arrays.asList("test1", "test2"));
}

此代码将始终在您运行的任何其他测试之前执行。 这对于定义执行测试的特定顺序很有用。

您应该在每次测试之前创建您正在测试的 class 的新实例。

因此,您的测试 class 将如下所示:

class MyTests {
  private MyService myService;

  @Before // junit 4, or @BeforeEach for junit 5
  public void setup() {
    myService = new MyService(... pass mocks of dependencies ...);
  }

  @Test
  public void aTest() {
    myService...
  }

  @Test
  public void aTest2() {
    myService... // this is a fresh instance of MyService, any changes to the
                 // state of the instance used in aTest() are gone.
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM