我有一个弹簧启动执行器,WebMvc测试不起作用。它返回一个空体。我该如何测试?
@Configuration
@ManagementContextConfiguration
public class TestController extends AbstractMvcEndpoint
{
public TestController()
{
super( "/test", false, true );
}
@GetMapping( value = "/get", produces = MediaType.APPLICATION_JSON_VALUE )
@ResponseBody
public OkResponse getInfo() throws Exception
{
return new OkResponse( 200, "ok" );
}
@JsonPropertyOrder( { "status", "message" } )
public static class OkResponse
{
@JsonProperty
private Integer status;
@JsonProperty
private String message;
public OkResponse(Integer status, String message)
{
this.status = status;
this.message = message;
}
public Integer getStatus()
{
return status;
}
public String getMessage()
{
return message;
}
}
}
当我尝试使用下面的测试时,它不起作用。我在回程中得到一个空身。
@RunWith( SpringJUnit4ClassRunner.class )
@DirtiesContext
@WebMvcTest( secure = false, controllers = TestController.class)
@ContextConfiguration(classes = {TestController.class})
public class TestTestController
{
private MockMvc mockMvc;
private ObjectMapper mapper;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setup()
{
//Create an environment for it
mockMvc = MockMvcBuilders.webAppContextSetup( this.webApplicationContext )
.dispatchOptions( true ).build();
mapper = new ObjectMapper();
}
@SpringBootApplication(
scanBasePackageClasses = { TestController.class }
)
public static class Config
{
}
@Test
public void test() throws Exception
{
//Get the controller's "ok" message
String response = mockMvc.perform(
get("/test/get")
).andReturn().getResponse().getContentAsString();
//Should be not null
Assert.assertThat( response, Matchers.notNullValue() );
//Should be equal
Assert.assertThat(
response,
Matchers.is(
Matchers.equalTo(
"{\"status\":200,\"message\":\"ok\"}"
)
)
);
}
}
答案 0 :(得分:0)
这是我写的一个测试,用来做你正在谈论的事情。该测试验证了我们唯一想要暴露的执行器端点是可用的。
这是使用SpringBoot 1.5。
我发现这里的问题很有用:Unit testing of Spring Boot Actuator endpoints not working when specifying a port。
@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(properties = {
"management.port="
})
public class ActuatorTests {
@Autowired
private WebApplicationContext context;
@Autowired
private FilterChainProxy springSecurityFilterChain;
private MockMvc mvc;
@Before
public void setup() {
context.getBean(MetricsEndpoint.class).setEnabled(true);
mvc = MockMvcBuilders
.webAppContextSetup(context)
.alwaysDo(print())
.apply(SecurityMockMvcConfigurers.springSecurity(springSecurityFilterChain))
.build();
}
@Test
public void testHealth() throws Exception {
MvcResult result = mvc.perform(get("/health")
.with(anonymous()))
.andExpect(status().is2xxSuccessful())
.andReturn();
assertEquals(200, result.getResponse().getStatus());
}
@Test
public void testRestart() throws Exception {
MvcResult result = mvc.perform(get("/restart")
.with(anonymous()))
.andExpect(status().is3xxRedirection())
.andReturn();
assertEquals(302, result.getResponse().getStatus());
assertEquals("/sso/login", result.getResponse().getRedirectedUrl());
}
}