Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify calls to dependency in unit test?

Tags:

For this following class I want to write a unit test:

public class SomeClass {

    private Dependency dependency;

    public SomeClass(Dependency dep){
        this.dependency = dep;
    }

    private String processString(String s){
        /*
        edit the string and return
         */
    }

    public void doSomething(String arg){

        String processed = processString(arg);

        dep.doSomethingElse(processed);
    }
}

At first I would stub all the methods SomeClass calls on Dependency in order to test my class in isolation. But the question I couldn't yet find an answer to is :

Should I check how SomeClass calls methods of Dependency e.g. what parameters are passed etc. ? Of course this is a pretty trivial example, but I want to know if this should be part of a unit test in general.

Edit: In my case Dependency would be third party api library which I dont control. So I would consider it important what parameters are passed to these functions however I'm not sure this should be part of a unit test.

like image 500
flxh Avatar asked Oct 05 '16 10:10

flxh


1 Answers

I would say that if dependency is invoked then you should have at least one test case to check if it is called. If you don't want to cover this case, that means (for me) you don't need to call it anyway. This is very important when you have any conditional statements like if/else/switch. Can you imagine that just by mistake you removed this line of code

 dep.doSomethingElse(processed);

Without checking if dependency was invoked you will even not notice that you removed it.

The test can looks like:

import static org.fest.assertions.Assertions.assertThat;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class SomeClassTest {

  @Mock
  private Dependency dependency;

  @InjectMocks
  private SomeClass someClass;

  @Captor
  private ArgumentCaptor<String> argumentCaptor;

  @Test
  public void shouldCallDependency() throws Exception {
    //given
    String arg = "arg";

    //when
    someClass.doSomething(arg);

    //then
    Mockito.verify(dependency).doSomethingElse(argumentCaptor.capture());
    assertThat(argumentCaptor.getValue()).isEqualTo("processed");
  }

}
like image 177
Rafał Krajnik Avatar answered Sep 25 '22 17:09

Rafał Krajnik