首页 > 解决方案 > Api 控制器的单元测试用例

问题描述

如何为此控制器编写 Junit 测试用例?

@PostMapping(path = "/appformsubmission")
    public AppFormChannelResponseObject saveAppForm(
            @RequestBody AppFormChannelRequestObject<AppFormDetails> requestObject) throws JsonProcessingException {

        logger.info("MwController -saveAppForm ");
        if (logger.isDebugEnabled()) {
            logger.debug("Entering MwController() method");
            logger.debug("requestObject : {}", Utility.toJsonString(requestObject));
        }
        return appFormService.submitApplicationForm(requestObject);
    }

如果我是 Junit 新手,如果能得到一个示例测试用例,那就太好了。提前致谢。

标签: spring-bootjunitcontroller

解决方案


来自 spring boot docs,通过使用 MockMvc 进行 MVC 层测试

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class AppFormChannelTest{

    @Autowired
    private MockMvc mvc;

    @Test
    public void saveAppFormTest() throws Exception {
      AppFormChannelRequestObject body=new AppFormChannelRequestObject();
      Gson gson = new Gson();
      String json = gson.toJson(body);

      this.mockmvc.perform(post("/appformsubmission/")
    .contentType(MediaType.APPLICATION_JSON).content(json))
    .andExpect(status().isOk());
    }

}

推荐阅读