如何使用具有LocalDate

时间:2018-12-15 17:23:31

标签: java spring spring-mvc junit

当我尝试使用硬编码对象测试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))));
    }
}

型号:

@实体 公共类Transit {

@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和其他一些方法,但仍然无法通过测试。谢谢您的宝贵时间。

2 个答案:

答案 0 :(得分:0)

尝试更改此行

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

对此:

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

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

答案 1 :(得分:0)

我在模型的日期中添加了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)”。