测试junit中抛出异常的方法

时间:2012-07-30 01:09:05

标签: exception junit

我正在测试一个在异常时重试不同参数的函数。以下是伪代码。

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

如何通过模拟externalAPI使用junit测试上面的代码。

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

但是上面的测试没有说“试图从一个方法(来自foo())抛出一个不会抛出异常的SomeException”。但实际上方法foo在其方法签名中提到了SomeException。

我如何为函数foo编写junit?

1 个答案:

答案 0 :(得分: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());   
}