如何使用PowerMock模拟Thread.sleep()?

时间:2013-10-21 12:27:27

标签: java testing mockito powermock

如何使用PowerMock模拟Thread.sleep()?

示例界面和类:

public interface Machine {

    void sleep(long millis);
}

public class MachineImpl
implements Machine {

    private static final Logger logger = Logger.getLogger(MachineImpl.class);

    @Override
    public void sleep(long millis) {
        try {
            if (millis > 0) {
                logger.trace(String.format("Try to sleep for %d millis...", millis));
                Thread.sleep(millis);
            }
        }
        catch (InterruptedException e) {
            logger.trace("Full exception", e);
        }
    }
}

2 个答案:

答案 0 :(得分:10)

我花了一些时间才弄明白,所以我回答了自己的问题。

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)  // important
@PrepareForTest(MachineImpl.class)  // important: do not use Thread.class here
public class MachineImplTest {

    private MachineImpl classUnderTest;

    @Before
    public void beforeEachTest() {
        classUnderTest = new MachineImpl();
    }

    @Test
    public void sleep_Pass() {
        classUnderTest.sleep(0);
        classUnderTest.sleep(-100);
        classUnderTest.sleep(+100);
    }

    @Test
    public void sleep_Pass2() {
        // We do not want to mock all methods, only specific methods, such as Thread.sleep().
        // Use spy() instead of mockStatic().
        PowerMockito.spy(Thread.class);

        // These two lines are tightly bound.
        PowerMockito.doThrow(new InterruptedException()).when(Thread.class);
        Thread.sleep(Mockito.anyLong());

        classUnderTest.sleep(0);
        classUnderTest.sleep(-100);
        classUnderTest.sleep(+100);
    }
}

答案 1 :(得分:5)

这很有帮助。我最终使用的东西略有不同。我使用EasyMock而不是Mockito。

@RunWith(PowerMockRunner.class)
@PrepareForTest({ClassUnderTest.class})
public class MyTest {
    @Before
    public void setUp() {
        PowerMock.mockStatic(Thread.class, methods(Thread.class, "sleep"));
        Thread.sleep(anyLong());
        EasyMock.expectLastCall().anyTimes();
    }
}

无需在Thread.class中使用@PrepareForTest