Reputation: 9269
I am testing a function which retries with different parameters on exception. Following is the pseudo code.
class Myclass {
public void load(input)
try {
externalAPI.foo(input);
} catch(SomeException e) {
//retry with different parameters
externalAPI.foo(input,input2);
}
How can I test above code using junit by mocking 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));
}});
}
But above test fails saying "tried to throw a SomeException from a method(from foo()) that throws no exceptions". But actually the method foo has mentioned SomeException in its method signature.
How can i write junit for the function foo?
Upvotes: 1
Views: 255
Reputation: 1467
With Mockito, I would do it like this: ...
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());
}
Upvotes: 1