Is it possible to freeze System.currentTimeMillis() for testing

前端 未结 6 2464
孤街浪徒
孤街浪徒 2021-02-20 02:24

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

6条回答
  •  情歌与酒
    2021-02-20 03:07

    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.

提交回复
热议问题