Here is how you would do it with EasyMock 3.0 (and 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();
}
}
The only problem with the test above is that the Runtime
object needs to be passed to code under test, which prevents it from using Runtime.getRuntime()
.
With JMockit, on the other hand, the following test can be written, avoiding that problem:
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");
}
}