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.
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");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With