简体   繁体   中英

Is this a unit test or integration test?

I am learning how to create a unit test in Spring Boot JPA with JUnit and Mockito

I have done up a test class,

public void testInsertionMethod() throws Exception {

    String URI = "/insertionURL";
    ShoppingList list = new ShoppingList (3, new Fruit(1), new Vegetable(1));
    String inputJson= this.jsonConversionMethod(list);

    Assert.assertEquals(1, list.getNumOfItems());
    Assert.assertEquals(1, list.getFruit().getFruitId);
    Assert.assertEquals(1, list.getVegetable.getVegetableId());

    Mockito.when(shoppingListSvc.save(Mockito.any(ShoppingList.class))).thenReturn(list);

    MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.post(URI).param("fruitId", "1").param("vegId", "1"). accept(MediaType.APPLICATION_JSON).content(inputJson).contentType(MediaType.APPLICATION_JSON)).andReturn();

    MockHttpServletResponse mockHttpServletResponse = mvcResult.getResponse();
    String jsonOutput = mockHttpServletResponse.getContentAsString();
    assertThat(outputJson).isEqualTo(inputJson);
    Assert.assertEquals(HttpStatus.OK.value(), mockHttpServletResponse.getStatus());

}

Can anyone advise on how I can improve my unit testing? Am I doing anything wrong here?

It's a component test. Also your test class is probably annotated with

@AutoConfigureMockMvc
@SpringBootTest

cause you are using mockMvc to mock a call to endpoint.

In my opinion it does not make sense to do this part

 Assert.assertEquals(1, list.getNumOfItems());
 Assert.assertEquals(1, list.getFruit().getFruitId);
 Assert.assertEquals(1, list.getVegetable.getVegetableId());

cause you created this object in the test and you know what did you put there. The only thing you should be interested in is what your endpoint returns. You can check it as you already do via comparing inputJson and outputJson or do it like this:

        .andExpect(status().isOk())
        .andExpect(jsonPath("$.id", equalTo(...)))
        .andExpect(jsonPath("$.firstName", notNullValue()))
        .andExpect(jsonPath("$.lastName").isNotEmpty())
        .andExpect(jsonPath("$.email", equalTo(...)))
        .andExpect(jsonPath("$.partnerId", equalTo(...)));

Depends on what is important for you to check. Eg if your response returns id which is generated by some internal class/method you will not be able to construct such inputJson cause you cannot predict which id will be returned. In this case you are able to check that id is not empty

        .andExpect(jsonPath("$.id").isNotEmpty())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM