Issue
I am writing unit tests for a class, and I need to mock a call to a method in the same class.
//My class:
public class Class {
public void functionA(arguments){
...
String s3 = functionB(s1, s2);
}
public String functionB(String s1, String s2){
...
return s3;
}
}
//My Test:
@Test
public void functionA_Test(){
Class class = new Class(dependency);
Class spyClass = spy(class);
mockString = "this is a mock";
when(spyClass.functionB(any(),any()).thenReturn(mockString);
spyClass.functionA(arguments);
}
When I debug the test function, after reaching when(spyClass.functionB(any(),any()).thenReturn(mockString);
, the program jumps to the main class, inside functionB
, to run it. What I want is to automatically assign s3=mockString
when calling functionB
from functionA
.
Solution
When calling when(spyClass.functionB(any(),any()).thenReturn(mockString)
, it will indeed go through the real method in debug mode. But the method is mocked, and your functionA
gets the mockString
. It does work. I don't really understand why seing that you can go into debug mode into it is a problem.
To answer the question, using mock
won't go through the method:
Class mockClass = mock(Class.class);
when(mockClass.functionB(any(),any())).thenReturn(mockString);
when(mockClass.functionA(arguments)).thenCallRealMethod();
mockClass.functionA(arguments);
BUT : this is a really bad test, you should never need to do that (spy or mock). If you test a class, then you test all of it. If you need to mock a method to test another one, one of them probably belongs to another class.
Answered By - Anne
Answer Checked By - Timothy Miller (JavaFixing Admin)