Issue
I have a function that is calling a method from another class. This class and method have been tested and are using live data which makes my test inconsistent with the expected values I hard coded.
public class MyClass{
public void functionToBeTested(String params){
//stuff to do
Caller call = new Caller();
callResult = call.post(someJSON);
//do stuff with callResult
}
}
Here is the junit:
public class TestMyClass{
MyClass testClass = new MyClass();
Caller mock;
@Before
public void setup(){
premadeAnswer = new String(file);
mock = Mockito.mock(Caller.class);
Mockito.when(mock.post(Mockito.any())).thenReturn(premadeAnswer);
}
@Test
public void studentFees_CorrectSSN(){
assertEquals(expected.getThing(), testClass.functionToBeTested("PARAMS").getThing());
}
}
I was pretty sure I did everything right but obviously its not mocking and instead calling the function ans behaving as expected if it wasn't a junit. If I had to make a guess as to whats happening it would be that even though I am creating a mocked object and using when/thenReturn it is not attached to MyClass testClass object.
Solution
That won't work because Caller
is not injected into functionToBeTested
function.
Mockito.when(mock.post(Mockito.any())).thenReturn(premadeAnswer);
this when statement is working only on your mocked instance, inside functionToBeTested
you are creating a new instance of Caller
.
Either change functionToBeTested(String params)
to functionToBeTested(String params, Caller call)
and then pass your mocked Caller
instance or try mocking Caller
constructor.
More info about second approach here
Answered By - Mershel
Answer Checked By - David Marino (JavaFixing Volunteer)