3

I'm testing if doSomething method is again getting called in catch block when exception occurs. How to validate if 'doSomething' got called twice ?

Class to be tested:

@Service
public class ClassToBeTested implements IClassToBeTested {

@Autowired
ISomeInterface someInterface;

public String callInterfaceMethod() {
 String respObj;
 try{
     respObj = someInterface.doSomething(); //throws MyException
 } catch(MyException e){
    //do something and then try again
    respObj = someInterface.doSomething();
 } catch(Exception e){
    e.printStackTrace();
  }
 return respObj;
 }
}

Test Case:

public class ClassToBeTestedTest
{
@Tested ClassToBeTested classUnderTest;
@Injectable ISomeInterface mockSomeInterface;

@Test
public void exampleTest() {
    String resp = null;
    String mockResp = "mockResp";
    new Expectations() {{
        mockSomeInterface.doSomething(anyString, anyString); 
        result = new MyException();

        mockSomeInterface.doSomething(anyString, anyString); 
        result = mockResp;
    }};

    // call the classUnderTest
    resp = classUnderTest.callInterfaceMethod();

    assertEquals(mockResp, resp);
}
}
Pankaj
  • 3,512
  • 16
  • 49
  • 83
  • How about this? http://stackoverflow.com/questions/7700965/equivalent-of-times-in-jmockit – toy Sep 28 '15 at 21:22
  • Check this Q&A. http://stackoverflow.com/questions/14889951/how-to-verify-a-method-is-called-two-times-with-mockito-verify ... Essentially, it's verify(mockObject, times(3)).someMethod("was called exactly three times"); – HulkSmash Sep 28 '15 at 21:23
  • @toy It partially works. I have to remove the second mock call under Expectation. I could verify the call count but now i wouldn't be able to verify if i got the expected response from catch block. How to verify both together – Pankaj Sep 28 '15 at 22:10
  • @DV88 this is Mockito example, i'm looking for something in JMockit. – Pankaj Sep 28 '15 at 22:10

1 Answers1

3

The following should work:

public class ClassToBeTestedTest
{
    @Tested ClassToBeTested classUnderTest;
    @Injectable ISomeInterface mockSomeInterface;

    @Test
    public void exampleTest() {
        String mockResp = "mockResp";
        new Expectations() {{
            // There is *one* expectation, not two:
            mockSomeInterface.doSomething(anyString, anyString);

            times = 2; // specify the expected number of invocations

            // specify one or more expected results:
            result = new MyException();
            result = mockResp;
        }};

        String resp = classUnderTest.callInterfaceMethod();

        assertEquals(mockResp, resp);
    }
}
Rogério
  • 16,171
  • 2
  • 50
  • 63