@deterb が示唆したように、Mockito では可能ですが、メソッド名を知っているか、すべてのメソッドに期待値を設定する必要があります。次に例を示します。
モックされたインターフェース:
public interface MyInterface {
void allowedMethod();
void disallowedMethod();
}
キャッチするユーザークラスAssertionError
:
public class UserClass {
public UserClass() {
}
public static void throwableCatcher(final MyInterface myInterface) {
try {
myInterface.allowedMethod();
myInterface.disallowedMethod();
} catch (final Throwable t) {
System.out.println("Catched throwable: " + t.getMessage());
}
}
}
そしてMockitoテスト:
@Test
public void testMockito() throws Exception {
final MyInterface myInterface = mock(MyInterface.class);
UserClass.throwableCatcher(myInterface);
verify(myInterface, never()).disallowedMethod(); // fails here
}
EasyMock でも同じことが可能ですが、いくつかの作業が必要です。
@Test
public void testEasyMock() throws Exception {
final AtomicBoolean called = new AtomicBoolean();
final MyInterface myInterface = createMock(MyInterface.class);
myInterface.allowedMethod();
myInterface.disallowedMethod();
final IAnswer<? extends Object> answer = new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
System.out.println("answer");
called.set(true);
throw new AssertionError("should not call");
}
};
expectLastCall().andAnswer(answer).anyTimes();
replay(myInterface);
UserClass.throwableCatcher(myInterface);
verify(myInterface);
assertFalse("called", called.get()); // fails here
}
myInterface.disallowedMethod()
残念ながら、ここではメソッド名も知っている必要があり、や などの期待値を定義する必要がありますexpectLastCall().andAnswer(answer).anyTimes()
。
もう 1 つの可能性は、Proxy
クラスを使用して( customInvocationHandler
を使用して) プロキシを作成し、それをモック オブジェクトとして使用することです。確かにもっと作業が必要ですが、最もカスタマイズ可能なソリューションになる可能性があります。
最後に、EasyMock モック オブジェクトへの委任の有無にかかわらず、カスタム実装を作成することも可能であることを忘れないでください。ここに委任のあるものがあります:
public class MockedMyInterface implements MyInterface {
private final MyInterface delegate;
private final AtomicBoolean called = new AtomicBoolean();
public MockedMyInterface(final MyInterface delegate) {
this.delegate = delegate;
}
@Override
public void allowedMethod() {
delegate.allowedMethod();
}
@Override
public void disallowedMethod() {
called.set(true);
throw new AssertionError("should not call");
}
public boolean isCalled() {
return called.get();
}
}
そしてそれのためのテスト:
@Test
public void testEasyMockWithCustomClass() throws Exception {
final MyInterface myInterface = createMock(MyInterface.class);
myInterface.allowedMethod();
final MockedMyInterface mockedMyInterface =
new MockedMyInterface(myInterface);
replay(myInterface);
UserClass.throwableCatcher(mockedMyInterface);
verify(myInterface);
assertFalse("called", mockedMyInterface.isCalled()); // fails here
}