Mock Runtime.getRuntime()?

前端 未结 4 766
爱一瞬间的悲伤
爱一瞬间的悲伤 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:55

    Bozho above is IMO the Correct Solution. But it is not the only solution. You could use PowerMock or JMockIt.

    Using PowerMock:

    package playtest;
    
    public class UsesRuntime {
        public void run() throws Exception {
            Runtime rt = Runtime.getRuntime();
            rt.exec("notepad");
        }
    }
    
    
    package playtest;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.legacy.PowerMockRunner;
    
    import static org.powermock.api.easymock.PowerMock.*;
    import static org.easymock.EasyMock.expect;
    
    @RunWith(PowerMockRunner.class)
    @PrepareForTest( { UsesRuntime.class })
    public class TestUsesRuntime {
    
        @Test
        public void test() throws Exception {
            mockStatic(Runtime.class);
            Runtime mockedRuntime = createMock(Runtime.class);
    
            expect(Runtime.getRuntime()).andReturn(mockedRuntime);
    
            expect(mockedRuntime.exec("notepad")).andReturn(null);
    
            replay(Runtime.class, mockedRuntime);
    
            UsesRuntime sut = new UsesRuntime();
            sut.run();
        }
    }
    

提交回复
热议问题