【发布时间】: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