java: how to mock Calendar.getInstance()?

前端 未结 6 896
忘了有多久
忘了有多久 2020-12-03 16:54

In my code I have something like this:

private void doSomething() {
   Calendar today = Calendar.getInstance();
   ....
}

How can I \"mock\

6条回答
  •  温柔的废话
    2020-12-03 17:40

    Don't mock it - instead introduce a method you can mock that gets dates. Something like this:

    interface Utility {
    
        Date getDate();
    }
    
    Utilities implements Utility {
    
    
        public Date getDate() {
    
            return Calendar.getInstance().getTime();
        }
    
    }
    

    Then you can inject this into your class or just use a helper class with a bunch of static methods with a load method for the interface:

    public class AppUtil {
    
        private static Utility util = new Utilities();
    
        public static void load(Utility newUtil) {
    
             this.util = newUtil;
        }
    
        public static Date getDate() {
    
            return util.getDate();
        }
    
    }
    

    Then in your application code:

    private void doSomething() {
       Date today = AppUtil.getDate();
       ....
    }
    

    You can then just load a mock interface in your test methods.

    @Test
    public void shouldDoSomethingUseful() {
         Utility mockUtility = // .. create mock here
         AppUtil.load(mockUtility);
    
         // .. set up your expectations
    
         // exercise the functionality
         classUnderTest.doSomethingViaAPI();
    
         // ... maybe assert something 
    
    }
    

    See also Should you only mock types you own? and Test smell - everything is mocked

提交回复
热议问题