JimBob91
JimBob91

Reputation: 11

Take JSONObject as a parameter in Mockito mock method

I am trying to use Mockito to mock a method for my JUnit testing. The Method takes a JSONObject from simple-json as a parameter and responds with a JSONObject. The method I am tring to mock is from another class and the code I am testing calls it. I can not seem to get Mockito to catch my request and respond accordingly. Am I completely missing something here?

public class TestClass{
  JSONObject jsonRequest;
  JSONObject jsonReturn;

  AnotherClass anotherClass = Mockito.mock(AnotherClass.class);

  @Before
  public void setUp(){
    jsonRequest = this.readJSONFromFile("jsonRequest.json");
    jsonReturn = this.readJSONFromFile("jsonReturn.json");
    Mockito.when(anotherClass.anotherClassMethod(jsonRequest)).thenReturn(jsonReturn);
  }

  @Test
  public void testMethod(){
     TestClass testClass = new TestClass();
     assertEquals(testClass.method(jsonRequest), jsonReturn);
  }
}

Upvotes: 1

Views: 21249

Answers (3)

Mehmudjan Mehmet
Mehmudjan Mehmet

Reputation: 19

You mocked the method of the mock object, but in your test class, instead of using mock object testClass, you instantiated a new TestClass object which won't be intercepted by Mockito. Plus the last line of your code doesn't look right,

assertEquals(testClass.method(jsonRequest, jsonReturn));

Ok. Your testMethod should look something like:

@Test
public void testMethod(){
   assertEquals(testClass.method(jsonRequest), jsonReturn);
}

Hope this helps.

Upvotes: 1

Michael Dodd
Michael Dodd

Reputation: 10270

You're mocking the wrong method signature. You have a mock set up for method(JSONObject) but are calling method(JSONObject, JSONObject) (note the two arguments). You'll either need to mock the two-argument method, or only call the one-argument method in the test.

I'd also recommend changing the mock to accept any instance of a JSONObject:

Mockito.when(testClass.method(any(JSONObject.class)).thenReturn(jsonReturn);

Finally, as mentioned by Mehmudjan Mehmet, remove the new instance of TestClass from your test as otherwise your mocks won't work. You should be using the instance declared at the top of your test.

Upvotes: 2

jonhid
jonhid

Reputation: 2125

I think you have wrong the assert

 assertEquals(testClass.method(jsonRequest), jsonReturn);

Upvotes: 0

Related Questions