Spring MockMvc - 请求参数列表

Jay*_*Jay 4 java spring spring-mvc

我正在尝试使用 MockMvc 测试几个控制器端点,但遇到了一些麻烦(请客气点,我是新手......)。使用字符串作为参数的简单端点工作正常,但使用字符串列表的稍微复杂一点的端点不满意并抛出异常;有人能指出我做错了什么吗?

@RestController
@RequestMapping("/bleh")
public class Controller
{
    @Autowired
    private DataService dataService

    @RequestMapping(value = "/simple", method = RequestMethod.GET)
    public String simple(String name) 
    { 
        return dataService.getSomeData(name) 
    }

    @RequestMapping(value = "/complicated", method = RequestMethod.GET)
    public String complex(List<String> names)
    { 
        return dataService.getSomeOtherData(names) 
    }
}
Run Code Online (Sandbox Code Playgroud)

——

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class HealthControllerTests extends Specification
{
    def dataServiceMock;
    def testController;
    def mockMvc;


    def setup(){
        dataServiceMock = Mock(DataService)
        dataServiceMock.getSomeData >> "blaah"
        testController = new Controller(dataService: dataServiceMock)
        mockMvc = MockMvcBuilders.standaloneSetup(testController).build();
    }

    def "working test"
        when:
        def response = MockMvc.perform(get("/simple").param("name", "tim"))
                .andReturn()
                .getResponse();

        then:
        response.status == OK.value();
        response.contentAsString == "blaah"

    def "unhappy test"
        when:
        def response = MockMvc.perform(get("/complicated").param("names", new ArrayList<>()))
            .andReturn()
            .getResponse();

        then:
        response.status == OK.value()


}
Run Code Online (Sandbox Code Playgroud)

抛出这个:

No signature of method: org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder.param() is applicable for argument types: (java.lang.String, java.util.ArrayList) values: [names, []]. Possible solutions: param(java.lang.String, [Ljava.lang.String;), params(org.springframework.util.MultiValueMap), wait(), grep(), any(), putAt(java.lang.String, java.lang.Object)])
Run Code Online (Sandbox Code Playgroud)

Sea*_*oll 5

不支持 ArrayList 但您可以执行以下操作

def "complicated test"
    when:
    def response = MockMvc.perform(get("/complicated").param("names", "bob", "margret"))
        .andReturn()
        .getResponse();

    then:
    response.status == OK.value()

def "another complicated test"
        when:
        def response = MockMvc.perform(get("/complicated").param("names", new String[]{"bob", "margret"}))
            .andReturn()
            .getResponse();

        then:
        response.status == OK.value()
Run Code Online (Sandbox Code Playgroud)