Dantinho
Dantinho

Reputation: 57

The test Junit and Mockito gives me errors when analyzing the dates with hours

I'm having trouble validating if everything jsonPath is doing is right for my controller. I am new to the testing area and I have taken a referral site, but there are many things in the design that are very characteristic, so it is difficult to find some answers. If anyone can help me, I would be grateful. Code:

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:

@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);

}

Error

java.lang.AssertionError: JSON path "$.dateInit" Expected: is Tue (Jan 03 02:00:02 BRST 2017) but: was "2017-01-03 04:00:02"

Then it adds 2 hours at the end of the execution, how to solve this problem?

Upvotes: 1

Views: 148

Answers (1)

Corey Schnedl
Corey Schnedl

Reputation: 175

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

is not correct. Should probably be yyyy-MM-dd.

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

Upvotes: 1

Related Questions