【发布时间】:2016-11-25 02:48:41
【问题描述】:
最近我更改了 Spring Boot 属性以定义管理端口。 这样做,我的单元测试开始失败:(
我编写了一个单元测试来测试 /metrics 端点,如下所示:
@RunWith (SpringRunner.class)
@DirtiesContext
@SpringBootTest
public class MetricsTest {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
/**
* Called before each test.
*/
@Before
public void setUp() {
this.context.getBean(MetricsEndpoint.class).setEnabled(true);
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
/**
* Test for home page.
*
* @throws Exception On failure.
*/
@Test
public void home()
throws Exception {
this.mvc.perform(MockMvcRequestBuilders.get("/metrics"))
.andExpect(MockMvcResultMatchers.status().isOk());
}
}
以前这是通过的。添加后:
management.port=9001
测试开始失败:
home Failed: java.lang.AssertionError: Status expected: <200> but was: <404>
我尝试更改 @SpringBootTest 注释:
@SpringBootTest (properties = {"management.port=<server.port>"})
server.port 使用的号码在哪里。这似乎没有任何区别。
然后将属性文件中的 management.port 值更改为与 server.port 相同。结果一样。
让测试工作的唯一方法是从属性文件中删除 management.port。
有什么建议/想法吗?
谢谢
【问题讨论】:
-
因此为成功和失败案例添加了一些跟踪日志记录。在成功的情况下,我看到以下内容:
TRACE [Test worker] --- org.springframework.test.web.servlet.TestDispatcherServlet: Testing handler map [org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping@2281521a] in DispatcherServlet with name这在失败的情况下丢失了。所以我只能假设我使用了错误的值MockMvcBuilders.webAppContextSetup(this.context)
标签: java spring-boot junit spring-boot-actuator