【问题标题】:How to write JUnit test with hardcoded object possesing LocalDate如何使用具有 LocalDate 的硬编码对象编写 JUnit 测试
【发布时间】:2018-12-15 17:23:30
【问题描述】:

当我尝试使用硬编码的对象测试我的 Api 控制器时,一切都很好,我尝试将 LocalDate 参数添加到对象。

我的测试:

@RunWith(SpringRunner.class)
@WebMvcTest(ApiTransitController.class)
public class ApiTransitControllerTest {


    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private TestService testService;

    @MockBean
    private ReportsService reportsService;

    @MockBean
    private TransitService transitService;

    @Test
    public void shouldCreateTransit() throws Exception {

        Transit transit = new Transit("London", "Paris", 12L, 
    LocalDate.of(2018,10,12));

        ObjectMapper objectMapper = new ObjectMapper();
        String transitJsonString = objectMapper.writeValueAsString(transit);


        this.mockMvc.perform(post("/api/transit")
                .contentType(MediaType.APPLICATION_JSON)
                .content(transitJsonString))
                .andExpect(status().isCreated());

        verify(transitService).addTransit(eq(new Transit("London", "Paris", 12L, 
   LocalDate.of(2018,10,12))));
    }
}

型号:

@实体 公共类公交{

@Column(name = "id")
@Id
@GeneratedValue
private Long id;
private String sourceAdress;
private String destinationAdress;
private Long price;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private LocalDate date;
@JsonSerialize(using=DistanceSerializer.class)
private Long distance;

 public Transit(String sourceAdress, String destinationAdress, Long price, LocalDate date) {
        this.sourceAdress = sourceAdress;
        this.destinationAdress = destinationAdress;
        this.price = price;
        this.date = date;
    }

//getters and setters, equals and hashCode and toString

API 控制器:

 @PostMapping("/api/transit")
    @ResponseStatus(HttpStatus.CREATED)
    public void createTransit(@RequestBody Transit transit){
        LOG.info("Saving transit={}", transit);
        transitService.addTransit(transit);
    }

我尝试了添加 DateTimeFormmater 和其他一些方法,但我仍然无法通过测试。感谢您的宝贵时间。

【问题讨论】:

  • 可能 Locale.of(..) 返回一个新实例,在这种情况下对象将不相等

标签: java spring spring-mvc junit


【解决方案1】:

尝试改变这一行

verify(transitService).addTransit(eq(new Transit("London", "Paris", 12L, 
   LocalDate.of(2018,10,12))));

到这里:

verify(transitService).addTransit(eq(transit));

这两个对象不相等,你也不需要创建一个新的对象,你可以使用已经创建的对象。

【讨论】:

  • 没有改变,测试没有通过。
【解决方案2】:

我将 JsonSerializer 添加到模型的日期:

型号:

@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
@JsonSerialize(using=DateSerializerNumberTwo.class)
    private LocalDate date;

序列化器:

public class DateSerializerNumberTwo extends StdSerializer<LocalDate> {


    private static DateTimeFormatter formatter =
            DateTimeFormatter.ofPattern("yyyy-MM-dd");

    public DateSerializerNumberTwo(){
        this(null);
    }
    protected DateSerializerNumberTwo(Class<LocalDate> t){
        super(t);
    }

    @Override
    public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeString(formatter.format(value));
    }
}

并且测试通过,测试代码没有任何变化。我认为这是因为日期的 Json 默认响应是“yyyy,mm,dd”,而不是本地日期(yyyy-mm-dd)”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-05
    • 2014-03-19
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    • 2022-11-04
    相关资源
    最近更新 更多