0

Here is my code:

`public class Service {
   callSomeService(ContextTpye1 c1,Parameter p){
   //do something here
   ContextTpye2 c2 = constructContext(c1,p);      
   if(c2.timeout()){
      c2.audit();
     }
   }
 }`

In the unit test, the Service, Parameter and ContextTpye1 are initialized. Is it possible to only mock c2.audit()? I wanna it to doNothing here. Thanks.

gepoemrun
  • 21
  • 2
  • 1
  • possible duplicate of [Should I mock local method invocation inside a tested method?](http://stackoverflow.com/questions/23653583/should-i-mock-local-method-invocation-inside-a-tested-method) – Dave Schweisguth Jun 06 '14 at 23:20
  • 1
    They are different! Here another class was created and I only want a partial mock. Please read my question. – gepoemrun Jun 06 '14 at 23:48

1 Answers1

1

So the way I would attack the problem assuming constructContext(c1,p) is public is to when testing the Service class is to spy on the Service allowing you to mock the constructContext(c1,p) and returning a mock of ContextType2.

public class ServiceTest
{
    private Service service = Mockito.spy(new Service());

    private ContextType2 c2 = Mockito.mock(ContextType2.class);

    @Test
    public void testCallSomeService()
    {
        Mockito.when(service.constructContext(Mockito.eq(ContextType1.class), Mockito.eq(Parameter.class))).thenReturn(c2);
            Mockito.when(c2.timeout()).thenReturn(true);
        Mockito.when(c2.audit()).doNothing();
            service.callSomeService(new ContextType1(), new Parameter());
    }
}
ndrone
  • 3,524
  • 2
  • 23
  • 37
  • I cannot just do 'Mockito.when(c2.timeout()).thenReturn(true);' There are some calculation in c2 to give this value. – gepoemrun Jun 08 '14 at 04:37
  • 1
    What's the point then? Why are you testing ContextType2.timeout() in the service test case? If you want to test the timeout method create a test cases for the ContextType2 class. In the Service class test cases you should be testing service class methods, not the methods of other classes that the service class calls. – ndrone Jun 08 '14 at 12:29