EasyMock 3.0(およびJUnit 4)でこれを行う方法は次のとおりです。
import org.junit.*;
import org.easymock.*;
import static org.easymock.EasyMock.*;
public final class EasyMockTest extends EasyMockSupport
{
@Test
public void mockRuntimeExec() throws Exception
{
Runtime r = createNiceMock(Runtime.class);
expect(r.exec("command")).andReturn(null);
replayAll();
// In tested code:
r.exec("command");
verifyAll();
}
}
上記のテストの唯一の問題は、Runtime
オブジェクトをテスト対象のコードに渡す必要があることです。これにより、オブジェクトを使用できなくなりRuntime.getRuntime()
ます。一方、JMockitを使用すると、次のテストを記述して、その問題を回避できます。
import org.junit.*;
import mockit.*;
public final class JMockitTest
{
@Test
public void mockRuntimeExec() throws Exception
{
final Runtime r = Runtime.getRuntime();
new NonStrictExpectations(r) {{ r.exec("command"); times = 1; }};
// In tested code:
Runtime.getRuntime().exec("command");
}
}