0

I want to mock System.currentTimeMillis() method to return the mock value when generateFileName method called from MyClassImpl instance constructor.

...
...

public class MyClassImpl {
    private String myFileName;

    public MyClassImpl() {
        generateFileName();
    }

    public String getMyFileName() {
        return myFileName;
    }

    private void generateFileName() {
        myFileName = "Request" + System.currentTimeMillis();
    }
}
...
...

@RunWith(PowerMockRunner.class)
@PrepareForTest(System.class)
@PowerMockIgnore({"javax.management.*"})
public class MyClassImplTest {

    @Test
    public void testForFileSave() throws Exception {
        // Arrange
        PowerMockito.mockStatic(System.class);
        PowerMockito.when(System.currentTimeMillis()).thenReturn(123456789L);

        System.out.println(System.currentTimeMillis() + " mocked current time");

        // Act
        MyClassImpl myclass = new MyClassImpl();

        // Assert
        assertThat(myclass.getMyFileName(), is("Request" + System.currentTimeMillis()));
    }
}

Test response

123456789 mocked current time
ScriptEngineManager providers.next(): javax.script.ScriptEngineFactory: Provider jdk.nashorn.api.scripting.NashornScriptEngineFactory not a subtype
INFO 2021-03-05T07:45:32,390 org.eclipse.jetty.util.log [Test worker] Logging initialized @5103ms to org.eclipse.jetty.util.log.Slf4jLog


Expected: is "Request123456789"
     but: was "Request1614930331383"
Expected :Request123456789
Actual   :Request1614930331383

How to fix this issue?

1
  • What do you need to assert? Are the numbers absolutely necessary? Or would it suffice if you check that your fileName != null and .contains("Request")? I ran into the same problem many times myself with times/dates and it was never crucial to assert that they were exact (most of the times before/after checks were enough). Besides, if System fails, nothing works. So I really would rethink the value of such assertion
    – Paul
    Mar 5, 2021 at 13:11

1 Answer 1

1

Put System.currentTimeMillis() in a separate protected method. In the test create a test class that extends MyClassImpl and overrides the protected method, returning whatever you want for the test.

public class MyClassImpl {
    // ...

    private void generateFileName() {
        myFileName = "Request" + currentTimeMillis();
    }

    protected long currentTimeMillis() {
        return System.currentTimeMillis();
    }
}

public class MyClassMock extends MyClassImpl {
    @Override
    protected long currentTimeMillis() {
        return 123456789L;
    }
}

Instead of using this custom mock class, you can also use partial mocks (i.e. a spy in mockito).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.