Issue
I have my test cases failing for ZonedDateTime tests with an error. I am using JHipster generator 3.9.1
This is how dates to be used in tests are defined:
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);
Then in test method:
@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)));
}
Which gives the error:
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"
The test class definition uses Spring boot 1.4 annotations:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = NutrilifeApp.class)
public class MealResourceIntTest {
What's the best/valid approach to test ZonedDateTime with Spring Boot?
Solution
After some investigation I decided to follow @dunni proposed solution above and changed the test data to use UTC, the code changed to this:
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);
and the tests are now passing. For some reason the JHipster generator is adding tests for generated entities using system default timezone(ZoneId.systemDefault()), which cause tests using ZonedDateTime to fail.
Answered By - groo
Answer Checked By - Cary Denson (JavaFixing Admin)