DEV Community

Cover image for TDD and tests with Mocks

Posted on

TDD and tests with Mocks


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 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.


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

public void setup(){
    service = new RentService();
    RentDAO dao = Mockito.mock(RentDAO.class);
    spcService = Mockito.mock(SPCService.class);
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.

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

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

    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.


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:

Top comments (0)