0

I need your assistance please:

I have this method:

public class MyTestClass {

protected void foo(JSONObject result, String text){
        String userId = result.optString("name");
        mApi.sendInfo(userId, text, mListener);
    }
}

In Mockito I do:

@Test
public void whenFooIsCalledThenSendInfoGetsCalled(){
    MyTestClass testClassSpy = spy(mMyTestClass);
    JSONObject jsonOb = mock(JSONObject.class);
    when(jsonOb.optString("name")).thenReturn("something");

    testClassSpy.foo(eq(jsonOb), anyString());

    ....
    some verification....

The problem is, the when the foo method gets called, JSONObject result is null. I can't seem to get this to work. I thought that if I mock the object and make it return a String once optString("name") is called, would solve this issue but it seems NPE is all I get. What am I doing wrong?

Thanks you

Alon Minski
  • 1,571
  • 2
  • 19
  • 32

1 Answers1

1

I am not from Java world but when I look on this code snippet I'm not sure what you want to test. If you want to verify exactly what your test method suggest whenFooIsCalledThenSendInfoGetsCalled then:

  1. You should create spy for mApi
  2. You should create stub for JSONObject result
  3. You should use real implementation of MyTestClass

So your SUT class should allow for injecting dependencies:

public class MyTestClass {
   private mApi;
   public MyTestClass(Api api) {
       mApi = api;
   }

   void foo(JSONObject result, String text){ /* your implementation */}
}

And your test method:

@Test
public void whenFooIsCalledThenSendInfoGetsCalled(){
    // arrange test
    Api spyApi = spy(Api.class);
    JSONObjec stub = mock(JSONObject.class);
    when(stub.optString("name")).thenReturn("something");

    MyTestClass sut = new MyTestClass(spyApi);

    // Act
    sut.foo(stub, "text");

    // Assert
    verify(spyApi , times(1)).foo(eq("something"), "text", listener);
}
Piotr Pasieka
  • 2,063
  • 1
  • 12
  • 14