There is a Service
class and a Util
class with two static methods as shown.
public class Service {
public String doSomething() {
return "something";
}
}
public final class Util {
public static String utilFuncCallingService(Service service) {
//some code
System.out.println("Util class calling doSomething on service");
return service.doSomething();
}
public static String utilFuncReturningString() {
return "string";
}
}
The main class (SUT) is,
public class MyClass {
public final Service service;
public MyClass(Service service) {
this.service = service;
}
public void method() {
System.out.println("Response: " + Util.utilFuncCallingService(service));
}
}
It calls the Util.utilFuncCallingService
method passing the Service
instance.
The JUnit test is:
@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
@Mock
private Service service;
@Before
public void setup() {
when(Util.utilFuncCallingService(service))
.thenReturn("mock-response");
}
@Test
public void test() {
MyClass myClass = new MyClass(service);
myClass.method();
}
}
Running this, it prints,
Util class calling doSomething on service
Util class calling doSomething on service
Response: mock-response
The first line was printed during setup
of test and the second during actual test.
- How did the stub call
when(Util.utilFuncCallingService(service)).thenReturn(..)
become equivalent of writingwhen(service.doSomething()).thenReturn("mock-response")
here?
Mockito wouldn't have allowed us to stub Util.utilFuncReturningString()
since it is a static method. How did the stub call to Util.utilFuncCallingService()
work here?
I've worked with JUnit quite a lot, but I feel I'm missing something very basic here.