DEV Community

Cover image for TDD and tests with Mocks
pedro-henrique-arruzzo
pedro-henrique-arruzzo

Posted on

TDD and tests with Mocks

TDD

Test Driven Development is a way of developing your code where the test is created before the actual code. This is made to make sure that the development works. The test must be the first thing to be created so the code can be created around it.

A good way to make these tests is using Mockito.

Mockito

Mockito is a mocking framework that is frequently used in unit tests. Mocking an object simulates it's behavior. When this simulation is created, it makes possible to realize a test without the need to call a complex object, we call only the mocked object.

Exemples

It's necessary to initiate the mocks before the tests.

@Before
public void setup(){
    service = new RentService();
    RentDAO dao = Mockito.mock(RentDAO.class);
    service.setRentDao(dao);
    spcService = Mockito.mock(SPCService.class);
    service.setSpcService(spcService);
}
Enter fullscreen mode Exit fullscreen mode

I'm simulating the interfaces RentDAO and SPCService with Mockito.

RentDAO: public void save(Rent rent);
SPCService: public boolean isNegative(User user);

With this we can make our test calling the mock.

@Test
public void rentTest() throws Exception {
    //given
    User user = UserBuilder.aUser().now();
    List<Movie> movies = Arrays.asList(MovieBuilder.aMovie().withValue(5.0).now());

    //when
    Rent rent = service.rentMovie(user, movies);

    //then
    error.checkThat(rent.getValue(), is(equalTo(5.0)));
    error.checkThat(DataUtils.isSameDate(rent.getRentDate(), new Date()), is(true));
    error.checkThat(DataUtils.isSameDate(rent.getReturnDate(), DataUtils.obtainDataInDifferenceInDays(1)), is(true));
}
Enter fullscreen mode Exit fullscreen mode

In this test, a user and a movie where initiated and the rent service was mocked.

Conclusion

This way, it's possible to test if the rent service works without actually using it. That's useful to avoid, for example, unnecessary calls to the data base, just mock the object that make this call.

In case you are interested, here's the repository on GitHub, with more of these mocked tests: https://github.com/pedro-henrique-arruzzo/poc/tree/main/MockTests

Top comments (0)