2015-09-28 33 views
2

我正在測試如果doSomething方法再次在發生異常時在catch塊中調用。如何驗證'doSomething'是否被調用過兩次?時間API調用

類來進行測試:

@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; 
} 
} 

測試用例:

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); 
} 
} 
+0

這個怎麼樣? http://stackoverflow.com/questions/7700965/equivalent-of-times-in-jmockit – toy

+0

查看本問與答。 http://stackoverflow.com/questions/14889951/how-to-verify-a-method-is-called-two-times-with-mockito-verify ...實質上,它是驗證(mockObject,times(3)) .someMethod(「被稱爲三次」); – DV88

+0

@toy它部分地工作。我不得不在預期下刪除第二個模擬電話。我可以驗證呼叫計數,但現在我無法驗證我是否從catch block得到了預期響應。如何一起驗證 – Pankaj

回答

2

下面應該工作:

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); 
    } 
}