使用 Spring 引导 1.4 错误对 ZonedDateTime 进行集成测试

Integration Tests with ZonedDateTime using Spring boot 1.4 error

我的测试用例在 ZonedDateTime 测试中失败并出现错误。我正在使用 JHipster generator 3.9.1

测试中使用的日期是这样定义的:

private static final ZonedDateTime DEFAULT_DATE = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneId.systemDefault());
private static final String DEFAULT_DATE_STR = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(DEFAULT_DATE);

然后在测试方法中:

@Test
@Transactional
public void searchMeal() throws Exception {
    // Initialize the database
    mealService.save(meal);

    // Search the meal
    restMealMockMvc.perform(get("/api/_search/meals?query=id:" + meal.getId()))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$.[*].id").value(hasItem(meal.getId().intValue())))
        .andExpect(jsonPath("$.[*].title").value(hasItem(DEFAULT_TITLE)))
        .andExpect(jsonPath("$.[*].description").value(hasItem(DEFAULT_DESCRIPTION)))
        .andExpect(jsonPath("$.[*].picture").value(hasItem(DEFAULT_PICTURE)))
        .andExpect(jsonPath("$.[*].date").value(hasItem(DEFAULT_DATE_STR)));
}

给出错误:

java.lang.AssertionError: JSON path "$.[*].date"
Expected: a collection containing "1970-01-01T01:00:00+01:00"
 but: was "1970-01-01T00:00:00.000Z"

测试class 定义使用Spring boot 1.4 注释:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = NutrilifeApp.class)
public class MealResourceIntTest {

使用 Spring 启动测试 ZonedDateTime 的 best/valid 方法是什么?

经过一番调查,我决定遵循@dunni 上面提出的解决方案并将测试数据更改为使用UTC,代码更改为:

private static final ZonedDateTime DEFAULT_DATE = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
private static final String DEFAULT_DATE_STR = DateTimeFormatter.ISO_INSTANT.format(DEFAULT_DATE);

现在测试通过了。出于某种原因,JHipster 生成器正在使用系统默认时区(ZoneId.systemDefault())为生成的实体添加测试,这会导致使用 ZonedDateTime 的测试失败。