java 如何在SpringBoot测试中以编程方式获取方法URL?

j8ag8udp  于 2023-04-10  发布在  Java
关注(0)|答案(2)|浏览(129)

我想测试我的控制器

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class MyTest {

    @LocalServerPort
    int port;

    @Autowired
    TestRestTemplate rest;

    String myUrl = ...;

    @Test
    public void testSequence() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String requesString = ...
        HttpEntity<String> request = new HttpEntity<>( requesString, headers );
        String response = rest.postForObject(myUrl, request, String.class);

在这里,我需要用类似于

String.format("http://localhost:%d/my/endpint/path", port);

其中my/endpint/path依赖于我应用于控制器类及其方法的注解。
但是我可以通过编程方式派生出具有类名和方法名的类吗?

k10s72fa

k10s72fa1#

当然,您可以使用反射从REST控制器中提取@RequestMapping路径,并将其与其中的处理程序方法的路径组合在一起,但这真的不值得麻烦,并且将它们放入公共常量中并使用它们在测试中构造结果url要容易得多。
另外,在测试之前构造一个URL实际上是测试的一部分--你要检查你的API URL看起来是否像你期望的那样。

z2acfund

z2acfund2#

使用MvcUriComponentsBuilder
让我们和小猫一起玩:

@RestController
@RequestMapping("/api/v1/cats")
public class CatsController {

    @GetMapping("/childrenOf")
    public List<Cat> getChildrenOf(@RequestParam("mommy") String mommyName); //omitted

}


//import static omitted

{
    assertDoesNotThrow(()-> getMockMvc.perform(get(
        fromMethodCall(
            on(CatsController.class).getChildrenOf("luna")
        ).build().toUri()
    ))
}

以上结果转换为http://localhost/api/v1/cats/childrenOf/?mommy=luna
为了突出显示MvcUriComponentsBuilder的使用,我大量使用了换行符和缩进

相关问题