2012-07-30 46 views
1

我正在测试一个函数,该函数在异常时使用不同的参数重试。以下是伪代码。在junit中测试引发异常的方法

class Myclass { 
public void load(input) 
    try { 
    externalAPI.foo(input); 
} catch(SomeException e) { 
    //retry with different parameters 
    externalAPI.foo(input,input2); 
} 

如何使用junit通过嘲笑externalAPI来测试上面的代码。

@Test 
public void testServiceFailover(){ 

    m_context.checking(new Expectations() {{ 
     allowing (mockObjExternalAPI).foo(with(any(String.class))); 
     will (throwException(InvalidCustomerException)); 
     allowing (mockObjExternalAPI).foo(with(any(String.class),with(any(String.class))); 
     will (returnValue(mockResult)); 
    }}); 
} 

但上面的测试失败,说“试图抛出SomeException异常从一个方法(从foo())抛出没有例外”。但实际上,foo方法在其方法签名中提到了SomeException。

我该如何写函数foo的junit?

+0

什么模拟框架您使用的? – walters 2012-09-21 09:39:05

回答

1

随着Mockito,我会做这样的: ...

private ExternalAPI mockExternalAPI; 
private MyClass myClass; 

@Before 
public void executeBeforeEachTestCase() 
{ 
    mockExternalAPI = Mockito.mock(ExternalAPI.class); 
    //Throw an exception when mockExternalAPI.foo(String) is called. 
    Mockito.doThrow(new SomeException()).when(mockExternalAPI).foo(Mockito.anyString()); 

    myClass = new MyClass(); 
    myClass.setExternalAPI(mockExternalAPI); 
} 

@After 
public void executeAfterEachTestCase() 
{ 
    mockExternalAPI = null; 
    myClass = null; 
} 

@Test 
public void testServiceFailover() 
{ 

    myClass.load("Some string); 

    //verify that mockExternalAPI.foo(String,String) was called. 
    Mockito.verify(mockExternalAPI).foo(Mockito.anyString(), Mockito.anyString()); 
} 
+0

如果你把测试方法中的sut和mock创造出来,它会看起来更干净:) – 2012-09-21 09:55:24

+0

谢谢阿德里安。请参阅上面的更新。 – walters 2012-09-21 10:05:06