How can I test method with void return using JUnit?

2

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

    
asked by anonymous 24.03.2016 / 20:09

2 answers

7

You test the side effects caused by the method. For example if your method void 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, for 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);
   }
}
    
24.03.2016 / 20:24
1

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

Often, these methods belong to classes with dependencies. Classic situation when 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 if the user has changed:

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

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

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 usuario has changed, but that our service has been called.

    
31.07.2018 / 13:36