[英]How to set the context path in Spring Boot WebMvcTest
我正在嘗試從我的 Spring Boot 應用程序測試我的 Rest 控制器,並希望控制器在與生產相同的路徑下可用。
例如我有以下控制器:
@RestController
@Transactional
public class MyController {
private final MyRepository repository;
@Autowired
public MyController(MyRepository repository) {
this.repository = repository;
}
@RequestMapping(value = "/myentity/{id}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<Resource<MyEntity>> getMyEntity(
@PathVariable(value = "id") Long id) {
MyEntity entity = repository.findOne(id);
if (entity == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(entity, HttpStatus.OK);
}
}
在我的application.yml
我已經為應用程序配置了上下文路徑:
server:
contextPath: /testctx
我對此控制器的測試如下所示:
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = MyController.class, secure=false)
public class MyControllerTest {
@Autowired
private MyRepository repositoryMock;
@Autowired
private MockMvc mvc;
@Test
public void testGet() throws Exception {
MyEntity entity = new MyEntity();
entity.setId(10L);
when(repositoryMock.findOne(10L)).thenReturn(entity);
MockHttpServletResponse response = this.mvc.perform(
MockMvcRequestBuilders.get("/testctx/myentity/10"))
.andReturn().getResponse();
assertEquals(response.getStatus(), 200);
}
@TestConfiguration
public static class TestConfig {
@Bean
MyRepository mockRepo() {
return mock(MyRepository.class);
}
}
}
此測試失敗,因為呼叫的狀態代碼為 404。 如果我調用/myentity/10
它會起作用。 不幸的是,其余調用是由 CDC-Test-Framework (pact) 發起的,因此我無法更改請求的路徑(包含上下文路徑/testctx
)。 那么有沒有辦法告訴 spring boot 測試在測試期間也用定義的上下文路徑啟動其余端點?
你可以試試:
@WebMvcTest(controllers = {MyController.class})
@TestPropertySource(locations="classpath:application.properties")
class MyControllerTest {
@Autowired
protected MockMvc mockMvc;
@Value("${server.servlet.context-path}")
private String contextPath;
@BeforeEach
void setUp() {
assertThat(contextPath).isNotBlank();
((MockServletContext) mockMvc.getDispatcherServlet().getServletContext()).setContextPath(contextPath);
}
protected MockHttpServletRequestBuilder createGetRequest(String request) {
return get(contextPath + request).contextPath(contextPath)...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.