Search code examples
javaunit-testingjmockit

JMockit mocking System.currentTimeMillis()


Running this test:

@Test
public void testSystemCurrentTimeMillis() {
    new NonStrictExpectations(System.class) {{
        System.currentTimeMillis(); result = 1438357206679L;
    }};
    long currentTime = System.currentTimeMillis();
    assertEquals(1438357206679L, currentTime);
}

I get an 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)

What's wrong with my Test (JMockit 1.18)?


Solution

  • Like so many things with JMockit, it's easy enough to do. Try this..

    @Test
    public void testSystemCurrentTimeMillis(@Mocked final System unused) {
        new NonStrictExpectations() {{
            System.currentTimeMillis(); result = 1438357206679L;
        }};
        long currentTime = System.currentTimeMillis();
        assertEquals(1438357206679L, currentTime);
    }
    

    Found this site to be an excellent reference, by the way. Probably you were tripped up by the static method. All you need to do is declare the class with the static method as mocked--you never need to refer to the variable, hence I named it "unused".