【问题标题】:The test Junit and Mockito gives me errors when analyzing the dates with hours在用小时分析日期时,测试 Junit 和 Mockito 给了我错误
【发布时间】:2017-07-06 02:42:17
【问题描述】:

我无法验证 jsonPath 所做的一切是否适合我的控制器。我是新来的测试区,拿了一个推荐网站,但是设计中有很多东西很有特点,所以很难找到一些答案。如果有人可以帮助我,我将不胜感激。代码:

package test

public class FormControllerTest {

  private MockMvc mockMvc;

  @Mock
  private FormServiceImpl formService;

  @Mock
  private UserServiceImpl userService;


  @InjectMocks
  private FormController formController;

  @Before
  public void init() {
    MockitoAnnotations.initMocks(this);

    mockMvc = MockMvcBuilders
            .standaloneSetup(formController)
            .build();
  }

测试:

@Test
public void test_get_Form_success() throws Exception {

    SimpleDateFormat formato = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");

    Date data = formato.parse("2017-01-03 02:00:02");
    Date data2 = formato.parse("2017-01-05 02:00:02");

    Form form = new Form().id(1).name("formTest")
            .active(true).description("Formtesting")
            .dateInit(data).dateEnd(data2);

    //List<Form> forms = Arrays.asList(form.dateInit(data).dateEnd(data2));
    //System.out.println(form.getDateEnd());

    when(formService.findOneForm(form.getId())).thenReturn(form);

    mockMvc.perform(get("/form/{id}",form.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(jsonPath("$.id", is(1)))
            .andExpect(jsonPath("$.name", is("formTest")))
            .andExpect(jsonPath("$.active", is(true)))
            .andExpect(jsonPath("$.description", is("Formtesting")))
            .andExpect(jsonPath("$.dateInit", is(form.getDateInit())))
            .andExpect(jsonPath("$.dateEnd", is(form.getDateEnd())));

    verify(formService, times(2)).findOneForm(form.getId());
    verifyNoMoreInteractions(formService);

}

错误

java.lang.AssertionError:JSON 路径“$.dateInit”预期:是周二(1 月 03 02:00:02 BRST 2017) 但是:是“2017-01-03 04:00:02”

那么它在执行结束时增加了2小时,这个问题怎么解决?

【问题讨论】:

    标签: java junit mockito


    【解决方案1】:
    SimpleDateFormat formato = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
    

    不正确。应该是 yyyy-MM-dd。

    见:https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

    【讨论】:

    • 我改了,还是一样的错误,怎么办?
    猜你喜欢
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-16
    • 2022-01-08
    • 2013-11-01
    相关资源
    最近更新 更多