【问题标题】:Is this a unit test or integration test?这是单元测试还是集成测试?
【发布时间】:2021-12-19 08:31:37
【问题描述】:

我正在学习如何使用 JUnit 和 Mockito 在 Spring Boot JPA 中创建单元测试

我已经完成了一个测试课,

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

}

谁能建议我如何改进我的单元测试?我在这里做错了吗?

【问题讨论】:

  • 单元测试,顾名思义,就是测试一个“单元”。与外部依赖项隔离并自行测试的类或一段代码。一旦您需要模拟其他依赖项的行为,它就不再是一个简单的单元测试。除此之外,你的问题是什么?如果您正在寻找对测试的改进,您可以查看codereview.stackexchange.com

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


【解决方案1】:

这是一个组件测试。此外,您的测试类可能带有注释

@AutoConfigureMockMvc
@SpringBootTest

因为您使用 mockMvc 来模拟对端点的调用。

在我看来,做这部分没有意义

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

因为你在测试中创建了这个对象并且你知道你在那里放了什么。您唯一应该感兴趣的是端点返回的内容。您可以通过比较 inputJson 和 outputJson 来检查它,或者这样做:

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

取决于您要检查的重要内容。例如。如果您的响应返回由某些内部类/方法生成的 id,您将无法构造这样的 inputJson,因为您无法预测将返回哪个 id。在这种情况下,您可以检查 id 是否为空

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

【讨论】:

  • 感谢您的意见和建议。我的另一个问题是,什么时候例外在这里发挥作用?像 NullPointerException 等。我怎么知道什么时候需要它?
  • 好吧,我将在单元测试中测试那部分......例如您的服务无法通过 Id 找到某些内容,您可能会收到 EntityNotFoundException,或者某些对象为空,您可能会收到 NPE。在单元测试中,您正在检查 EntityNotFoundException exception = assertThrows(EntityNotFoundException.class, () -> service.getSomething(WRONG_ID)); 然后您可以检查消息 `assertEquals(exception.getMessage(), MessageFormat.format("Entity with id {0} not found.", WRONG_ID));` 并验证没有调用其他方法,例如verify(anotherService, never()).save(any());
猜你喜欢
  • 2014-09-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-13
  • 2011-05-15
  • 2019-02-02
  • 1970-01-01
  • 2015-11-20
  • 1970-01-01
相关资源
最近更新 更多