spring-boot - 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 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());
}
}
推荐阅读
- c# - verticalNormalizedPosition 不精确或计算错误
- reactjs - React useState 落后了一步
- swift - 如何防止颜色在 Swift 的集合视图单元格中重复?
- ios - 如何检测汉堡菜单中子视图中的点击
- c++ - 为什么 A 构造函数被调用一次?
- c++ - 为什么相似的代码有不同的运行时和内存使用?
- node.js - 如何抑制导入文件中的 Jest Linter 错误?
- python-3.x - 为什么我的 HTTP 代理没有连接到 HTTPS 网站?
- android - 如何捏缩放我从 viewpager 适配器显示的图像
- excel - 查找并替换“=”为“=”直到最后一个工作表