Mockito - deep stubbing

java, junit, mockito

Solution

Yes of course, you are mixing real objects and mocks. Plus using the `thenCallRealMethod` lloks like a partial mock, it feels wrong here, it's no wonder the javadoc of this method talks about that as well.

I definatelty should stress you than, design wise, having a mock that returns a mock is often a smell. More precisely you are breaking the Demeter Law, or not following the Tell, Don't Ask principle.

Any looking at your code I don't why the code would need to mock `WebServiceTemplate`. You want to unit test `MyService`, and I don't see a relationship to `WebServiceTemplate`. Instead you should focus on the interactions with you helper only. And unit test `SomeHelper` separately where you'll be able to check the interactions between `SomeHelper` and `WebServiceTemplate`.

Here's a little example of how I see the thing:

public void ensure_helper_is_used_to_invoke_a_RequestObject() {
  // given a service that has an helper collaborator
  ... other fixture if necessary

  // when
  myService.behaviorToTest();

  // then
  verify(someHelperMock).invokeMeth(isA(RequestObject.class));
}

How those that look for your real use case ?

Hope that helps

Problem

I am using Mockito to test my classes. I am trying to use Deep stubbing as I didn't a way on injecting a Mock inside another mock object in Mockito. ``` class MyService{ @Resource SomeHelper somehelper; public void create() { //.... somehelper.invokeMeth(t); } } class SomeHelper{ @Resource private WebServiceTemplate webServiceTemplate; public void invokeMeth(T t) { try{ //... webServiceTemplate.marshalSendAndReceive(t); }catch (final WebServiceIOException e) { throw new MyAppException("Service not running"); } } } ``` Now I am trying to Unit test the MyService class's create() method. I have injected a mock for SomeHelper as follows ``` @Mock(answer = Answers.RETURNS_DEEP_STUBS) SomeHelper somehelper; ``` What I want now is when the invokeMeth() method gets called on the mocked somehelper object it calls the real method in this case. ``` when(somehelper.invokeMeth(isA(RequestObject.class))) .thenCallRealMethod(); ``` I was expecting the webServiceTemplate not be null in this case. However I get a Nullpointer exception when the code tries to execute the line ``` webServiceTemplate.marshalSendAndReceive(t); ``` Any clue how I can get access to a deep mock object (i.e. mock within a mock - in this case webserviceTemplete mock inside somehelper mock) and then apply a when condition to throw a WebserviceIOException ? I want this so that I can test the MyService.create() to check it behaves properly when a WebServiceIOException is thrown down the code.

Original source