SpringBoot单元测试-Service方法未调用

cod*_*eek 3 java spring-boot spring-boot-test

我是单元测试的新手。参考谷歌后,我创建了一个测试类来测试我的控制器,如下所示:

@RunWith(SpringRunner.class)
@WebMvcTest(PromoController.class)
public class PromoApplicationTests {
    @Autowired
    protected MockMvc mvc;
    @MockBean PromoService promoService;
   
   
   protected String mapToJson(Object obj) throws Exception {
      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.writeValueAsString(obj);
   }
   protected <T> T mapFromJson(String json, Class<T> clazz)
      throws JsonParseException, JsonMappingException, IOException {
      
      ObjectMapper objectMapper = new ObjectMapper();
      return objectMapper.readValue(json, clazz);
   }
   
   @Test
    public void applyPromotionTest_1() throws Exception {
           String uri = "/classPath/methodPath";
           List<Cart> cartLs = new ArrayList<Cart>();
          // added few objects to the list
           
           String inputJson = mapToJson(cartLs);
           MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri)
              .contentType(MediaType.APPLICATION_JSON).content(inputJson)).andReturn();
           
           int status = mvcResult.getResponse().getStatus();
           assertEquals(200, status);
           String actual = mvcResult.getResponse().getContentAsString();
           String expected = "{\"key1\":val1, \"key2\":\"val 2\"}";
           assertEquals(expected, actual, true);
            
    }
}
Run Code Online (Sandbox Code Playgroud)

我有以下控制器和服务类:

@RequestMapping("/classPath")
@RestController
public class PromoController {
    @Autowired
    PromoService promoService;
    
    @PostMapping("/methodPath")
    public PromoResponse applyPromo(@RequestBody List<Cart> cartObj) {
        PromoResponse p = promoService.myMethod(cartObj);
        return p;
    }
}

@Component
public class PromoServiceImpl implements PromoService{

    @Override
    public PromoResponse myMethod(List<Cart> cartList) {
        // myCode
    }

}
Run Code Online (Sandbox Code Playgroud)

当我调试单元测试时,控制器中的 p 对象为空。我得到的状态为 200,但不是预期的 JSON 响应

我在这里缺少什么?

Dea*_*ool 5

使用@WebMvcTest时,Spring Boot只会初始化Web层,而不会加载完整的应用程序上下文。并且您需要@MockBean在使用时创建和注入模拟@WebMvcTest

你已经做了什么

 @MockBean 
 PromoService promoService;
Run Code Online (Sandbox Code Playgroud)

Spring Boot 仅实例化 Web 层而不是整个上下文

我们使用 @MockBean 为 GreetingService 创建并注入模拟(如果不这样做,应用程序上下文将无法启动),并使用 Mockito 设置其期望。

但是,因为它是模拟 bean,所以你有责任模拟myMethod()调用

@Test
public void applyPromotionTest_1() throws Exception {
       String uri = "/classPath/methodPath";
       List<Cart> cartLs = new ArrayList<Cart>();
      // added few objects to the list

      // create PromoResponse object you like to return
      When(promoService.myMethod(ArgumentsMatchesr.anyList())).thenReturn(/*PromoResponse object */);
       
       String inputJson = mapToJson(cartLs);
       MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri)
          .contentType(MediaType.APPLICATION_JSON).content(inputJson)).andReturn();
       
       int status = mvcResult.getResponse().getStatus();
       assertEquals(200, status);
       String actual = mvcResult.getResponse().getContentAsString();
       String expected = "{\"key1\":val1, \"key2\":\"val 2\"}";
       assertEquals(expected, actual, true);
        
}
Run Code Online (Sandbox Code Playgroud)