Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Expectations redundant if I have Verifications in my test?

I'm confused as to the purpose of and difference between expectations and verifications. E.g.

@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);
    }};
}

First of all, please let me know if this test is poorly written/thought out.

Second, my question: the expectations section seems redundant to me, and I can't come up with an example where it wouldn't be.

like image 493
fred Avatar asked May 14 '15 00:05

fred


1 Answers

The purpose of Expectations is to allow a test to record expected results for mocked methods and/or constructors, as needed by the code under test.

The purpose of Verifications is to allow a test to verify expected invocations to mocked methods and/or constructors, as made by the code under test.

So, normally, a test wouldn't both record and verify the same expectation (where an "expectation" specifies a set of invocations to mocked methods/constructors that are expected to occur when the code under test is exercised).

With that in mind, the example test would look like this:

@Tested FooServiceImpl fooService;
@Injectable FooDao fooDao;

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

    new Verifications() {{ fooDao.delete(1L); }};
}
like image 55
Rogério Avatar answered Oct 30 '22 11:10

Rogério