spring - 使用MockMvc测试控制器时,出现参数传递错误
问题描述
我正在使用 MockMvc 来测试控制器。关于参数导入,我遇到了类型不匹配的问题。我尝试了所有的 json 样式。但没有任何效果
这是我的控制器类::
package app.dnatask.controller;
import ......;
@Slf4j
@RestController
@RequestMapping(value = "/API/scanresultconfigure")
public class ScanResultConfigureController extends BaseController {
@RequestMapping(value = "/queryScanResultList/{taskId}/{externalname}", method = RequestMethod.POST)
public IBaseResult queryscanResultList(final HttpServletRequest request, @PathVariable final String taskId, @PathVariable final String externalname, @RequestBody Map map) throws Exception {
return runController(new IControllRunner() {
public void run(IOutResult or, CheckResult cr) throws Exception {
......
}
}
}
}
这是我的测试课::
package app.dnatask.controller;
import ......
@WebAppConfiguration
@ContextConfiguration(classes = {ScanResultConfigureController.class})
@ComponentScan(
includeFilters = {
@ComponentScan.Filter(type = FilterType.CUSTOM,
value = {ScanResultConfigureController.class})
},
useDefaultFilters = false,
lazyInit = true
)
public class ScanResultConfigureControllerTest extends AbstractTestNGSpringContextTests {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@BeforeMethod
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).dispatchOptions(true).build();
System.out.println("UT starting.............");
}
@AfterMethod
public void am() {
System.out.println("UT ending.............");
}
@Test
public void testQueryscanResultList() throws Exception {
Map<String, String> testMap = new HashMap<>();
testMap.put("key1", "value1");
testMap.put("key2", "value2");
String requestJson = JSONObject.toJSONString(testMap);
mockMvc.perform(
post("/API/scanresultconfigure/queryScanResultList/001/abc")
.contentType(MediaType.APPLICATION_JSON)
.param("map", requestJson)
)
.andExpect(status().isOk())
.andDo(print());
}
}
错误信息::
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported
java.lang.AssertionError: Status expected:<200> but was:<415>
这是一个springmvc框架实现的项目,我使用TestNG进行单元测试。
解决方案
关于我的问题,解决方法如下:
MvcResult mvcResult = mockMvc.perform(
post("/API/scanresultconfigure/queryScanResultList/{taskId}/{externalname}", "123", "abc")
.contentType(MediaType.APPLICATION_JSON)
.content(requestJson)
)
.andExpect(status().isOk())
.andDo(print())
.andReturn();
推荐阅读
- swift - 重复调用 CoreData 后应用程序变慢
- android - 无法在 viewpager kotlin 中查看文本
- excel - 任务完成excel功能
- google-chrome - 编码的 UI 不会在 Chrome 中启动测试
- javascript - Possibility of adding html, css, js, ... to Go server?
- google-analytics - GTM 与 GA 中会话数据的差异
- spring - 未调用 Spring Boot Rest API 过滤器
- excel - vba MID 函数使我的撇号不可见
- python-3.x - Dash python plotly 实时更新表
- android - Android - Appium 的模拟位置将被 Wi-Fi、蓝牙和移动网络覆盖