【问题标题】:AssertionError when testing LocalDate with MockMvc and JUnit 5使用 MockMvc 和 JUnit 5 测试 LocalDate 时出现 AssertionError
【发布时间】:2020-08-02 03:04:23
【问题描述】:

我正在尝试在 Spring Boot 2.3 项目中将 JUnit 5 与 Hibernate 5.4 和 MockMvc 一起使用。

这就是我的employee 实体类的成员的样子:

import java.time.LocalDate;
... (Rest of the imports)

@Entity
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long employeeId;

    @Column(nullable = false, updatable = true)
    private String firstName;

    @Column(nullable = true, updatable = true)
    private String lastName;

    @Column(nullable = false, updatable = true)
    private String email;

    @Column(nullable = false, updatable = true)
    private LocalDate birthDate;

我正在尝试使用 JUnit 5 使用 Mockito 和 MockMvc 测试 LocalDate 字段birthDate。这是测试用例的样子:

    @Test
    public void testFindEmployeeById() throws Exception {
        Employee mockedEmployee = makeEmployee(9L, "Mock First", "Mock Last", "mock@email.com",
                LocalDate.of(1996, 9, 8), 9L, "Mock Project", "Mock Department");

        Mockito.when(employeeRepositoryMock.findById(mockedEmployee.getEmployeeId()))
                .thenReturn(Optional.of(mockedEmployee));

        mockMvc.perform(MockMvcRequestBuilders.get("/v1/employees/id/9").accept(MediaType.APPLICATION_JSON))
                .andDo(MockMvcRestDocumentation.document("employeeById",
                        Preprocessors.preprocessRequest(Preprocessors.prettyPrint()),
                        PayloadDocumentation.responseFields(
                                PayloadDocumentation.fieldWithPath("employeeId").description("Employee ID"),
                                PayloadDocumentation.fieldWithPath("firstName").description("First Name"),
                                PayloadDocumentation.fieldWithPath("lastName").description("Last Name"),
                                PayloadDocumentation.fieldWithPath("email").description("Email Address"),
                                PayloadDocumentation.fieldWithPath("birthDate").description("Date of Birth"),
                                PayloadDocumentation.fieldWithPath("project.projectId").description("Project ID"),
                                PayloadDocumentation.fieldWithPath("project.name").description("Project name"),
                                PayloadDocumentation.fieldWithPath("project.department.departmentId")
                                        .description("Department ID"),
                                PayloadDocumentation.fieldWithPath("project.department.name")
                                        .description("Department Name"))))
                .andDo(print()).andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$.employeeId").value(mockedEmployee.getEmployeeId()))
                .andExpect(MockMvcResultMatchers.jsonPath("$.firstName").value(mockedEmployee.getFirstName()))
                .andExpect(MockMvcResultMatchers.jsonPath("$.lastName").value(mockedEmployee.getLastName()))
                .andExpect(MockMvcResultMatchers.jsonPath("$.email").value(mockedEmployee.getEmail()))
                .andExpect(MockMvcResultMatchers.jsonPath("$.birthDate").value(mockedEmployee.getBirthDate()))
                .andExpect(MockMvcResultMatchers.jsonPath("$.project.projectId")
                        .value(mockedEmployee.getProject().getProjectId()))
                .andExpect(
                        MockMvcResultMatchers.jsonPath("$.project.name").value(mockedEmployee.getProject().getName()))
                .andExpect(MockMvcResultMatchers.jsonPath("$.project.department.departmentId")
                        .value(mockedEmployee.getProject().getDepartment().getDepartmentId()))
                .andExpect(MockMvcResultMatchers.jsonPath("$.project.department.name")
                        .value(mockedEmployee.getProject().getDepartment().getName()));
    }

在运行测试用例时,我得到一个 AssertionError:

java.lang.AssertionError: JSON path "$.birthDate" expected:<1996-09-08> but was:<1996-09-08>

如您所知,两种字符串表示形式是相同的。然而 JUnit 5 抛出了错误。

那么,将 LocalDate 与 JUnit 5 进行比较的正确方法是什么?

可以在这里找到类似的问题:Comparing LocalDate using Hamcrest in Junit Test Case 在这里:JUnit AssertionError when testing SimpledateFormat

提前致谢。 :)

【问题讨论】:

  • jsonPath 值只是一个字符串;在约会时尝试.toString()。另请注意,如果您使用静态导入,您的代码将显着地更易于阅读。
  • 做到了。请发表您的评论作为答案,以便我可以将其标记为已解决。非常感谢!另外,感谢有关使用静态导入的提示。

标签: java junit mockito mockmvc localdate


【解决方案1】:

JsonPath 对实际的 JSON 本身进行操作。此时,您的 LocalDate 已转换为 JSON string 值。虽然有一种说法是匹配器应该自动将 Java 值转换为字符串,但它不会,但是如果你调用 localDate.toString(),那么它应该可以工作。

(更一般地说,任何时候你得到一个匹配器错误,指出两个看起来相同的值不匹配,这可能是因为它们是具有共同toString()格式的不同类型。 )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-29
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多