首页 > 解决方案 > 运行junit测试时Rest API日期参数更改

问题描述

我已经使用 Spring 框架制作了一个 Rest API,该 API 将获取一个日期并从数据库中查找一条记录并返回该记录,在数据库中它将有一个开始日期和结束日期列,根据给定的日期,它应该返回给定日期介于两者之间的所有记录。

我正在使用 oracle 数据库 java 8 和 spring frome work boot 2.1.2 版本,问题是当我使用 Mokito 进行 junit 测试以测试我制作的 REST api 时,当我传入日期时,当我的方法收到日期时更改了日期,我发现当它收到转换为不同时区(+1 时区)的日期时,我的本地计算机时区设置为 -6 时区,如果我将日期转换为 +1,则测试将是成功,如果我只是传入日期对象,它会自动将其转换为 +1 时区,这将是不匹配的。

我想知道为什么,因为我在同一个地方测试它们,为什么日期仍然会改变,并且理解我更喜欢它的解决方案。

所以我将在数据库中有一个带有 product_category_id(long)、start_date(date)、end_date(date) 的表和带有 Product_id(long)、type_code(short)、price(double)、product_category_id 的第二个表,它们与 product_category_id 相关联

这是控制器文件中的方法

@GetMapping("/{startDate}")
  public ResponseEntity<List<ProductCategoryResource>> findByDate(
      @PathVariable("startDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) final Date startDate)
  {
    final List<ProductCategory> productCategoryList =
        ProductCategoryService.findByDate(startDate);

    final List<ProductCategoryResource> productCategoryResourceList = new ArrayList<>();

    for (final ProductCategory productCategory: productCategoryList)
    {
      productCategoryResourceList.add(new ProductCategoryResource(productCategory));
    }

    return new ResponseEntity<>(ProductCategoryResourceList, HttpStatus.OK);
  }

这是服务

public List<ProductCategory> findByDate(final Date searchDate)
  {

    return ProductCategoryRepository
        .findByStartDateLessThanEqualAndEndDateGreaterThanEqual(searchDate,
            searchDate);
  }

并且存储库只是扩展 CrudRepository 的默认接口,其中包含 findByStartDateLessThanEqualAndEndDateGreaterThanEqual 方法。

这是我的junit测试。

    public void findByDate() throws Exception{
    final String pattern = "yyyy-MM-dd";
    final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
    final Date searchDate = simpleDateFormat.parse("2018-05-22");

    //Here mock all return values and add to result list

    BDDMockito.given(ProductCategoryService.findByDate(searchDate)).willReturn(resultList);

    mvc.perform(MockMvcRequestBuilders.get("/productCategory/2018-05-22")
        .contentType(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(MockMvcResultMatchers.jsonPath("$[0].startDate", Matchers
            .startsWith(simpleDateFormat.format(resultList.get(0).getProductCategoryStartDate()))));
  }

所以这将给出一个错误 $[0].startDate is null,它没有返回模拟结果列表,我调试并发现当它点击控制器中的方法时,日期更改为 Mon May 21 18:00:00 CST 2018,所以日期与我在 BDDMockito.given 中给出的日期不匹配。但是如果我将我的本地时区更改为 +1,它将完全一样

我希望无论我在哪个时区运行项目的构建,测试都不会失败,它应该总是发送相同的日期,因为它实际上是通过 url 传递的。

标签: javaspringspring-mvc

解决方案


推荐阅读