1

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.

  • 1
    You create a new Caller object in your method. So it's not the same object as the mock in your test. Try to inject the Caller object into you class using DI. Or create a method getCaller() That returns the new Caller object. And then you can make a spy of your CUT (MyClass) and return a mock when getCaller is called. – Willem Jan 07 '20 at 14:02

2 Answers2

0

I noticed in your first block of code that you shared, that there is no return value specified. I added void in the code block below.

public class MyClass{
  public void functionToBeTested(String params){
    //stuff to do
    Caller call = new Caller();
    callResult = call.post(someJSON);
    //do stuff with callResult
  }
}
Vpaladino
  • 320
  • 2
  • 12
0

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

Mershel
  • 542
  • 1
  • 9
  • 17