简体   繁体   English

如何为Spring MVC端点创建包含所需请求参数的单元测试,该请求参数包含JSON字符串?

[英]How do you create a unit test for Spring MVC endpoint containing a required request parameter that contains a JSON string?

I understand that it is not good practice to have a request parameter that contains a JSON string but I have inherited this code so I have to work with it at the moment. 我知道,拥有包含JSON字符串的请求参数不是一个好习惯,但是我已经继承了此代码,因此目前我必须使用它。

I am trying to create a unit test to test this endpoint but I am having an issue with the item request parameter: 我正在尝试创建一个单元测试来测试此端点,但是项目请求参数存在问题:

The controller snippet is: 控制器代码段为:

    @RequestMapping(value = "/item/{idtype}:{id}/details",
            method = RequestMethod.GET, produces="application/json; charset=UTF-8")
    @ApiOperation(value = "",
            response = ItemDTO.class, responseContainer = "List")
    @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", value = "Authorization token",
            required = false, dataType = "string", paramType = "header")})
    public Collection<ItemDTO> getItemDetailList(@PathVariable("idtype") String idType, @PathVariable("id") String id,
                                                                   @RequestParam(value = "item", required = true) ItemDTO item {

   ...

   }
   ...
    @InitBinder("item")
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(ItemDTO.class, new StringArrayPropertyEditor(null));
    }

The binder is used to convert the JSON string passed in the item parameter, to the ItemDTO java object. 绑定器用于将在item参数中传递的JSON字符串转换为ItemDTO java对象。

The unit test snippet is: 单元测试代码段是:

private MockMvc mvc; 私人MockMvc mvc;

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    mvc = MockMvcBuilders.standaloneSetup(ItemDetailsController).build();
}
...
StringBuilder stringBuilder = new StringBuilder("/v2/item/").append("type").append(":").append("1234")
    .append("/details");
Map<String, String> value = new HashMap<>();
value.put("value", "{\"itemId\":\"test\"}");
URI uri = new URI(stringBuilder.toString());
UriComponents uriComponents = UriComponentsBuilder.fromUri(uri).query("item={value}").buildAndExpand(value);
mvc.perform(MockMvcRequestBuilders.get(uriComponents.toUri())
    .contentType(MediaType.APPLICATION_JSON_VALUE))
    .andExpect(MockMvcResultMatchers.status().isOk()

When I run the unit test I get the exception: 运行单元测试时,出现异常:

java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [biz.dto.ItemDTO]: no matching editors or conversion strategy found java.lang.IllegalStateException:无法将类型[java.lang.String]的值转换为所需的类型[biz.dto.ItemDTO]:未找到匹配的编辑器或转换策略

I have tried other permutations and combinations, such as using chaining the .param method to the .perform method of mvc to add the item parameter or just simply adding the item parameter to the Stringbuilder but I have not had any success. 我尝试了其他排列和组合,例如使用将.param方法链接到mvc的.perform方法以添加item参数,或者只是将item参数添加到Stringbuilder,但是我没有取得任何成功。 I have also tried searching the forum for similar questions but I have had no success there either. 我也曾尝试在论坛中搜索类似的问题,但我也没有成功。

Any help would be greatly appreciated. 任何帮助将不胜感激。

you are messing up your tests. 你搞砸了你的测试。

if you want to test binder - test binder. 如果要测试粘合剂,请测试粘合剂。 (mock test) if you want to test controller - test it. (模拟测试)是否要测试控制器-请对其进行测试。 (mock test, again) What you want is full integration test, to see that binder is used by annotation and then parses string (json) into proper class. (再次进行模拟测试)您想要的是完全集成测试,以查看批注是否使用活页夹,然后将字符串(json)解析为适当的类。 for that I would recommend RestAssured or something 为此,我会推荐RestAssured或其他东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在apache camel中对servlet端点进行单元测试? - How do you unit test a servlet endpoint in apache camel? 如何在Spring Rest MVC中强制使用bean请求参数? - How to force a bean request parameter to be required in Spring Rest MVC? Spring MVC 中不存在所需的字符串参数错误 - Required String parameter is not present error in Spring MVC 所需的字符串参数不存在 Spring MVC - Required String parameter is not present Spring MVC 发送多个参数 Ajax 字符串化请求时,所需的字符串参数“querycontent”不存在 - Required String parameter 'querycontent' is not present while sending multiple parameters Ajax stringify request with Jquery in Spring MVC Application 如何对Spring MVC带注释的控制器进行单元测试? - How to unit test a Spring MVC annotated controller? 如何为 Spring Boot Controller 端点编写单元测试 - How to write a unit test for a Spring Boot Controller endpoint 你如何在Eclipse中创建一个Spring MVC项目? - How do you create a Spring MVC project in Eclipse? 如何在Spring MVC中轻松创建表 - how do you easily create tables in spring mvc 如何使用 Spring MVC 控制器作为集成测试的假端点? - How do I use a Spring MVC Controller as a Fake Endpoint for an Integration Test?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM