For some testing purposes I would like to predict exactly what System.currentTimeMillis()
will return. Is there any way in which I can freeze or manually set what w
Yes, solution exists:
For testing purposes you may create your own wrapper System, for example
package my.pack;
import java.io.PrintStream;
public class System
{
// reuse standard System.out:
public static PrintStream out = java.lang.System.out;
// do anything with chosen method
public static long currentTimeMillis()
{
return 1234567;
}
}
and import it into your class which you want to test
import my.pack.System;
In that case all calls to System will be passed through your own System class.
NOTE:
This is a solution for "how to intercept System.currentTimeMillis()"
This is NOT suitable for automatic testing
This is NOT an example of "how-to-design-a-good-program". If you ask for a good design, then you need to refactor your code, replace System.currentTimeMillis() - see other answers.