How can I test method with void return using Junit?

Asked

Viewed 5,233 times

2

It is possible to perform automated testing, in Java, of a method that has return void using JUnit? If yes, how is it possible?

2 answers

7


You test the side-effects caused by the method. For example if your void method changes some attribute of the class the test should check if before the call the value of the attribute was X and after the call changed to Y, example:

class TarefaDeCasa {
    public String feita = "Não";

    public void perguntarNoStackoverflow() {
        this.feita = "Sim";
    }
}

public class TestJunit {
   @Test
   public void testPerguntarNoStackoverflow() {
        TarefaDeCasa t = new TarefaDeCasa();
        assertEquals("Não", t.feita);

        t.perguntarNoStackoverflow();
        assertEquals("Sim", t.feita);
   }
}

2

In addition to Bruno’s answer, it is worth adding another way to test methods that return void.

Often these methods belong to classes with dependencies. Classical situation when we are working with a service layer. Example:

class AlgumService {

    private final DependenciaService dependenciaService;

    public void alterar (Usuario usuario, String nome) {
        usuario.alterarNome(nome);
        dependenciaService.enviar(usuario);
    }
}

In the above method, you can check whether the user has been changed:

 AlgumService algumService = new AlgumService(mock(DependenciaService.class));
 Usuario usuario = new Usuario();
 algumService.alterar(usuario , "Joaquim");
 assert("Joaquim", usuario.getNome());

However, how to verify that the DependenciaService was called? With the help of a mock framework, we can do the verify of this:

DependenciaService dependenciaService = mock(DependenciaService.class)
AlgumService algumService = new AlgumService(dependenciaService );
Usuario usuario = new Usuario();
algumService.alterar(usuario , "Joaquim");

assert("Joaquim", usuario.getNome());
verify(dependenciaService ).enviar(any(Usuario.class));

And ensure not only that the usuario was changed, but that our service was called.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.