如果我的测试中有验证,期望是多余的吗?

fre*_*red 12 java testing junit unit-testing jmockit

我对期望和验证的目的和差异感到困惑.例如

@Tested FooServiceImpl fooService;
@Injectable FooDao fooDao;

@Test
public void callsFooDaoDelete() throws Exception {
    new Expectations() {{
        fooDao.delete(withEqual(1L)); times = 1;
    }};

    fooService.delete(1L);

    new Verifications() {{
        Long id;
        fooDao.delete(id = withCapture()); times = 1;
        Assert.assertEquals(1L, id);
    }};
}
Run Code Online (Sandbox Code Playgroud)

首先,如果这个测试写得不好,请告诉我.

第二,我的问题:期望部分对我来说似乎是多余的,我无法想出一个不会出现的例子.

Rog*_*rio 14

其目的Expectations是允许测试记录被测试代码所需的模拟方法和/或构造函数的预期结果.

其目的Verifications是允许测试验证对被模拟方法和/或构造函数的预期调用,如被测试代码所做的那样.

因此,通常,测试不会同时记录验证相同的期望(其中"期望"指定对被测试的代码被执行时预期发生的模拟方法/构造函数的一组调用).

考虑到这一点,示例测试将如下所示:

@Tested FooServiceImpl fooService;
@Injectable FooDao fooDao;

@Test
public void callsFooDaoDelete() throws Exception {
    fooService.delete(1L);

    new Verifications() {{ fooDao.delete(1L); }};
}
Run Code Online (Sandbox Code Playgroud)

  • 基本上,如果你想避免锅炉板代码和简单的"时间"式验证对你来说已经足够了,你可以把它放在期望块中,以使测试更容易开发和阅读.这可能会让您感到困惑,因为您在技术上验证了期望块,但就个人而言,我可以接受这一点,因为我看到了简单的好处. (2认同)