1

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

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?

4

1 回答 1

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());   
}
于 2012-09-21T09:47:34.460 回答