How do I write unit tests to make sure my date/time based code works for all time zones and with/out DST?

前端 未结 2 1578
长发绾君心
长发绾君心 2020-12-28 15:47

I\'m using JodaTime 2.1 and I\'m looking for a pattern to unit test code which performs date/time operations to make sure it behaves well for all time zones and independent

2条回答
  •  渐次进展
    2020-12-28 16:31

    for (String zoneId : DateTimeZone.getAvailableIDs())
    {
       DateTime testedDate1;
       DateTime testedDate2;
       try
       {
          final DateTimeZone tz = DateTimeZone.forID(zoneId);
          // your test with testedDate1 and testedDate2 
       }
       catch (final IllegalArgumentException e)
       {
          // catching DST problem
          testedDate1 = testetDate1.plusHours(1);
          testedDate2 = testetDate2.plusHours(1);
          // repeat your test for this dates
       }
    }
    

    Change for single test

    DateTimeZone default;  
    
    DateTimeZone testedTZ;
    
    @Before
    public void setUp()
    {
       default = GateTimeZone.getDefault();
       DateTimeZone.setDefault
    }  
    
    @After
    public void tearDown()
    {
       default = GateTimeZone.setDefault();
       DateTimeZone.setDefault(testedTZ)
    }   
    
    @Test
    public void test()
    {
    //...
    }
    

提交回复
热议问题