【问题标题】:Spring Boot WebMvc unit test date error: perform() returned date is earlier than expected(due to GMT assumption)Spring Boot WebMvc 单元测试日期错误:perform() 返回日期早于预期(由于 GMT 假设)
【发布时间】:2018-12-24 01:10:00
【问题描述】:

我正在使用 Spring Boot Test 框架 + Mockito 进行控制器单元测试。我发现测试失败是因为一个奇怪的错误:当我告诉 Mockito 返回一个带有java.util.Date 字段的对象时,响应总是有一个比预期早一天的日期字符串。

我的测试是这样的:

package com.mycompany.myapp.controller;

import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import com.privalia.binlookup.model.BinInfo;
import com.privalia.binlookup.repo.BinInfoRepository;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.MOCK, properties="classpath:test.properties")
@AutoConfigureMockMvc(secure=false)
public class BinInfoControllerUnitTests {
    @InjectMocks
    private BinInfoController controller;

    private MockMvc mockMvc;

    @MockBean
    private BinInfoRepository repository;

    private BinInfo mockBinInfo;

    @Before
    public void init() throws ParseException{
        SimpleDateFormat fmt = new SimpleDateFormat("dd/MM/yyyy");
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
        this.mockBinInfo = new BinInfo();
        this.mockBinInfo.setId(new Long(42));
        this.mockBinInfo.setBin("touhou");
        this.mockBinInfo.setJson_full("{is_json:true}");
        this.mockBinInfo.setCreateAt(fmt.parse("18/08/2018"));
    }


    @Test
    public void testBinInfoControllerSearchBIN() throws Exception {
        when(this.repository.findByBin("touhou")).thenReturn(mockBinInfo);

        this.mockMvc.perform(get("/search/touhou")
                .accept(MediaType.APPLICATION_JSON_UTF8_VALUE)
                .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(content().string(not("")))
            .andExpect(jsonPath("$.bin", is("touhou")))
            .andExpect(jsonPath("$.json_full", is("{is_json:true}")))
            .andExpect(jsonPath("$.createAt", is("18/08/2018")));
    }
}

我的控制器是:

package com.mycompany.myapp.controller;

import java.awt.MediaTracker;
import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.ResponseEntity.BodyBuilder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.privalia.binlookup.model.BinInfo;
import com.privalia.binlookup.repo.BinInfoRepository;

@RestController
@RequestMapping(value="/")
public class BinInfoController {

    @Autowired
    private BinInfoRepository repository;

    @RequestMapping(value="/search/{bin}", method=RequestMethod.GET)
    public ResponseEntity<BinInfo> searchBIN(@Valid @PathVariable String bin) {
        BinInfo found = repository.findByBin(bin);
        BodyBuilder builder = ResponseEntity.status(HttpStatus.OK);
        builder.contentType(MediaType.APPLICATION_JSON_UTF8);
        return (found == null ? builder.body(null) : builder.body(found));
    }

}

测试失败,因为返回的createAt字符串是17/08/2018,而不是18/08/2018。

我在时区“马德里/欧洲(格林威治标准时间 +0200,CEST)”,因为我们在夏季和 DST(夏令时),我怀疑某些时区的东西会干扰。

我的猜测:

模拟对象有一个没有时区信息的java.util.Date 对象,并且是8 月18 日00:00;当在perform() 中传递 Spring 上下文或 Jackson 或 Mockito 时,解析的 JSON 被视为 GMT,因此是负 2 小时,因此返回到 8 月 17 日。

但是我不知道在哪里可以找到相关的配置,是告诉Jackson,还是给Spring,或者Mockito不来做转换。

编辑:

原因确认:当我将日期字符串更改为18/08/2018 02:00:00 时,返回的日期为18/08/2018 00:00:00。

【问题讨论】:

    标签: java unit-testing spring-boot jackson mockito


    【解决方案1】:

    经过一番真正的挣扎后,我发现我必须在我的实体日期时间字段上使用OffsetDateTime,而在 PostgreSQL 中我必须使用timestamptz(带有时区的时间戳)。此外,要解析的日期时间字符串必须具有时区信息。

    Bean 字段:

    @NotNull
    @Column(name="updated_at", columnDefinition="TIMESTAMP WITH TIME ZONE")
    // Formats output date when this DTO is passed through JSON
    @JsonFormat(pattern="dd/MM/yyyy HH:mm:ss Z")
    // Allows date to be passed into GET request in JSON
    @DateTimeFormat(pattern="dd/MM/yyyy HH:mm:ss Z")
    @JsonProperty("updatedAt")
    /**
     * A timestamp object representing the moment the bininfo is updated.
     * In database we store the value with UTC timestamp, timestamptz.
     * When we save, local time will be converted to UTC, and when retrieve,
     * the offset is handled automatically.
     */
    private OffsetDateTime updatedAt;
    

    用于测试的对象构造:

    private String format; // 'dd/MM/yyyy HH:mm:ss Z'
    
    private String dateString; // '18/08/2018 02:00:00 +0200'
    
    @Before
    public void init() throws ParseException{
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
        this.mockBinInfo = new BinInfo();
        this.mockBinInfo.setId(new Long(42));
        this.mockBinInfo.setBin("touhou");
        this.mockBinInfo.setJson_full(this.json_full);
        this.mockBinInfo.setBrand(this.brand);
        this.mockBinInfo.setType(this.type);
        this.mockBinInfo.setCountry(this.country);
        this.mockBinInfo.setIssuer(this.issuer);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
        OffsetDateTime d = OffsetDateTime.parse(dateString, formatter);
        this.mockBinInfo.setCreatedAt(d);
        this.mockBinInfo.setUpdatedAt(d);
    }
    

    PostgreSQL 表列定义:

    updated_at | timestamp with time zone |
    

    以及保存的值:

    test1=# select * from bin_info;
    | .. |       updated_at
    +----+------------------------
    | .. | 2018-08-18 00:00:00+02
    

    请注意,在我的 JSON 中,时间戳为 02:00:00 +0200(带有时区偏移的本地时间),在 DB 中保存为 00:00:00+02(带有偏移的 GMT)。我没有更改 JVM 时区/语言环境/国家/地区设置。

    【讨论】:

      猜你喜欢
      • 2023-03-30
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 1970-01-01
      • 2020-10-27
      相关资源
      最近更新 更多