【问题标题】:Is there a way to get the "base URL" for a Controller in Spring when testing?测试时有没有办法在 Spring 中获取 Controller 的“基本 URL”?
【发布时间】:2020-06-18 15:31:59
【问题描述】:

我有一个看起来像这样的控制器类:

@RestController
@RequestMapping("controller")
public class Controller {
    @RequestMapping("foo")
    public String method() {
        return "foo'd the bar";
    }
}

我的测试是这样的:

@WebMvcTest(Controller.class)
public class ControllerTest {
    @Autowired
    private Controller controller;

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void canCreate() throws Exception {
        Assertions.assertThat(controller).isNotNull();
    }

    @Test
    public void canGetDummy() throws Exception {
        this.mockMvc.perform(get("/controller/foo")).andDo(print()).andExpect(status().isOk());
    }
}

这对我来说似乎有点脆弱,控制器的“基本 URL”至少在 n+1 位置硬编码为 n 测试方法。有没有办法配置测试来避免这种情况(所以我会写/foo而不是/controller/foo)?我可以使用静态变量,但似乎应该有更清洁的解决方案。

(或者我是不是在想这个错误,并且必须编写完整路径是好的 - 在这种情况下,为什么?)

【问题讨论】:

    标签: java spring-mvc


    【解决方案1】:

    完整路径 /controller/foo 是您正在测试的 Web API 的一部分。您可以根据需要将字符串部分提取为常量,但以一种或另一种方式直接将其包含在测试中是一件好事。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-25
      • 1970-01-01
      • 2015-10-18
      • 2015-09-06
      • 1970-01-01
      • 2021-08-14
      相关资源
      最近更新 更多