gpt4 book ai didi

java - Spring MockMvc - 请求参数列表

转载 作者:行者123 更新时间:2023-12-01 14:17:46 25 4
gpt4 key购买 nike

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

@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)
}
}

——
@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()


}

抛出这个:
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)])

最佳答案

不支持 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()

关于java - Spring MockMvc - 请求参数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45044021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com