DEV Community

Cover image for Unit Tests with JUnit
pedro-henrique-arruzzo
pedro-henrique-arruzzo

Posted on

Unit Tests with JUnit

Unitary tests are extremely necessary in any application to guarantee its functionality during the development. This tests must be done in a simple and fast way, so they can bem executed many times without taking a long time. Also, they must be independent, which means that one test shouldn't affect the results of another. And they should be repeatable.
These tests must reach to every scenery possible that the application will be used.

For example, your application offers a service of movie renting. Your tests must simulate this service in many different situations, like, changing quantities, prices, etc.

Now lets talk a little about JUnit, which is the main tool for the execution of unitary tests.

JUnit is an extremely important framework, because, with him, we can create tests to verify the functionality of classes and its methods. Besides that, he is responsible for the execution of these tests. This way, every time that the code has been changed, these tests can be executed to guarantee the integrity of the application.

Example:

I made a simple code of a movie renting service, and i want to make a test.

Three entities were created: Movie, Renting and User.

Here's the RentingService:

public class RentService {

    public Rent rentMovie(User user, List<Movie> movies)
            throws FilmeSemEstoqueException, LocadoraException {
        if(user == null) {
            throw new LocadoraException("Empty user");
        }

        if(movies == null || movies.isEmpty()) {
            throw new LocadoraException("Empty movie");
        }

        for (Movie movie : movies) {
            if (movie.getStock() == 0) {
                throw new FilmeSemEstoqueException();
            }
        }

        Rent rent = new Rent();
        rent.setMovies(movies);
        rent.setUser(user);
        rent.setRentDate(new Date());
        Double totalValue = 0d;
        for (Movie movie : movies){
            totalValue += movie.getRentPrice();
        }
        rent.setValue(totalValue);

        //Next day return
        Date returnDate = new Date();
        returnDate = adicionarDias(returnDate, 1);
        rent.setReturnDate(returnDate);

        //Salvando a locacao... 
        //TODO adicionar método para salvar

        return rent;
    }
}
Enter fullscreen mode Exit fullscreen mode

Now with the entities and the service created we can make the tests.

@Test
    public void rentTest() throws Exception {
        //given
        User user = new User("User 1");
        List<Movie> movies = Arrays.asList(new Movie("Movie 1", 1, 5.0));

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

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

First, we must create the scenery of the test, initializing the entities and giving them a value, we call this "Given".

User user = new User("User 1");
List<Movie> movies = Arrays.asList(new Movie("Movie 1", 1, 5.0));
Enter fullscreen mode Exit fullscreen mode

With the "Given" created, we'll make the action we want to test, in this case, rent a movie, we call this "When".

Rent rent = service.rentMovie(user, movies);
Enter fullscreen mode Exit fullscreen mode

At last, it's necessary that we verify if everything is working, we call this "Then".

error.checkThat(rent.getValue(), is(equalTo(5.0))); error.checkThat(isMesmaData(rent.getRentDate(), new Date()), is(true)); error.checkThat(isMesmaData(rent.getReturnDate(), obterDataComDiferencaDias(1)), is(true));
Enter fullscreen mode Exit fullscreen mode

Conclusion

With this, it's possible to create tests in different scenarios and make sure your application won't break with an alteration on the code.

If anyone is interested, the code is on GitHub

Top comments (0)