验收测试增量值

Acceptance testing an incrementing value

我有一项服务,其中 returns 创建文件的 ID,然后它递增 ID 以识别下一个文件。对于验收测试,我们有不同的项目,因此当我 运行 测试时,只有在第一次调用此服务时它才会通过。有什么解决方法可以用来解决这个问题吗?

@Test
public void createFileServiceTest(){
    int id = service.createFile("test.xml");

    assertEquals(0, id);
}

您的测试与您对服务的 specification/verbal 解释不符。因此,您不应该寻找解决方法,而应该彻底重新设计测试(或服务,或两者)。

重新设计测试,例如

@Test
public void creatingAFileTwiceShouldYieldDifferentIDs(){
    int id1 = service.createFile("test.xml");
    int id2 = service.createFile("test.xml");

    assertThat(id1, not(equalTo(id2)));
}

@Test
public void creatingFilesShouldYieldSuccessiveIDs(){
    int id1 = service.createFile("test1.xml");
    int id2 = service.createFile("test2.xml");

    assertThat(id1+1, is(equalTo(id2)));
}

重新设计两者,使服务更易于测试,例如

@Test
public void resetServiceShouldResetGetMaxId(){
    service.reset();
    assertThat(service.getMaxId(), is(equalTo(0)));
}

@Test
public void getMaxIdShouldYieldLatestId(){
    int id = service.createFile("test.xml");
    int newMaxId = service.getMaxId();

    assertThat(id, is(equalTo(newMaxId)));
}

@Test
public void creatingFilesShouldYieldSuccessiveIDs(){
    int oldMaxId = service.getMaxId();
    int id = service.createFile("test.xml");

    assertThat(oldMaxId+1, is(equalTo(id)));
}

当然,如果您可以并发访问该服务,则应保证测试的原子性,或者将检查从(a+1==b)弱化为(a<b)

如果我没理解错的话,可以试试这样检查:

@Test
public void createFileServiceTest(){
    Integer id = service.createFile("test.xml");

    assertNotNull(id);
    assertTrue(id > 0);

    Integer id2 = service.createFile("test2.xml");
    assertNotNull(id2);
    assertTrue(id2 > 0);

    assertTrue(id2 > id);
}