Mock Runtime.getRuntime()?

前端 未结 4 779
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-30 02:33

Can anyone make any suggestions about how best to use EasyMock to expect a call to Runtime.getRuntime().exec(xxx)?

I could move the call into a method i

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-30 02:53

    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");
        }
    }
    

提交回复
热议问题