Compare Date objects with different levels of precision

前端 未结 19 1981
日久生厌
日久生厌 2020-12-08 13:01

I have a JUnit test that fails because the milliseconds are different. In this case I don\'t care about the milliseconds. How can I change the precision of the assert to i

相关标签:
19条回答
  • 2020-12-08 13:32

    Instead of using new Date directly, you can create a small collaborator, which you can mock out in your test:

    public class DateBuilder {
        public java.util.Date now() {
            return new java.util.Date();
        }
    }
    

    Create a DateBuilder member and change calls from new Date to dateBuilder.now()

    import java.util.Date;
    
    public class Demo {
    
        DateBuilder dateBuilder = new DateBuilder();
    
        public void run() throws InterruptedException {
            Date dateOne = dateBuilder.now();
            Thread.sleep(10);
            Date dateTwo = dateBuilder.now();
            System.out.println("Dates are the same: " + dateOne.equals(dateTwo));
        }
    
        public static void main(String[] args) throws InterruptedException {
            new Demo().run();
        }
    }
    

    The main method will produce:

    Dates are the same: false
    

    In the test you can inject a stub of DateBuilder and let it return any value you like. For example with Mockito or an anonymous class which overrides now():

    public class DemoTest {
    
        @org.junit.Test
        public void testMockito() throws Exception {
            DateBuilder stub = org.mockito.Mockito.mock(DateBuilder.class);
            org.mockito.Mockito.when(stub.now()).thenReturn(new java.util.Date(42));
    
            Demo demo = new Demo();
            demo.dateBuilder = stub;
            demo.run();
        }
    
        @org.junit.Test
        public void testAnonymousClass() throws Exception {
            Demo demo = new Demo();
            demo.dateBuilder = new DateBuilder() {
                @Override
                public Date now() {
                    return new Date(42);
                }
            };
            demo.run();
        }
    }
    
    0 讨论(0)
提交回复
热议问题