运行这个测试:
@Test
public void testSystemCurrentTimeMillis() {
new NonStrictExpectations(System.class) {{
System.currentTimeMillis(); result = 1438357206679L;
}};
long currentTime = System.currentTimeMillis();
assertEquals(1438357206679L, currentTime);
}
我得到一个 IllegalStateException:
java.lang.IllegalStateException: Missing invocation to mocked type at this point; please make sure such invocations appear only after the declaration of a suitable mock field or parameter at unittests.DateTest$1.(DateTest.java:24) at unittests.DateTest.testSystemCurrentTimeMillis(DateTest.java:23)
我的测试 (JMockit 1.18) 有什么问题?
最佳答案
我的最终解决方案是为 System 创建一个 MockUp,它只模拟 currentTimeMillis() 方法:
private static class SystemMock extends MockUp<System> {
@Mock
public static long currentTimeMillis() {
return 10000000L;
}
}
@Test
public void testAddNowDate() {
new SystemMock();
long currentTime = System.currentTimeMillis();
assertEquals(10000000L, currentTime);
}
关于java - JMockit 模拟 System.currentTimeMillis(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31750244/