【发布时间】:2020-04-20 22:06:27
【问题描述】:
我有一个正在尝试测试的 REST 控制器,但在尝试向其发布时,我得到一个 404。测试是 JUnit 5 和 Spring Boot 2.1.5。如果我运行应用程序,我可以通过 Postman 访问控制器。我已经在调试模式下运行它并验证myController 不为空,并且已将模拟服务注入其中。我在这里想念什么? spring-boot-starter-test 是依赖,junit4 是排除。
@RestController
@Slf4j
@RequestMapping(path = /integrations,
produces = "application/json")
public class MyController {
private MyService myService;
private MyValidationService myValidationService;
public MyController(MySerivce service, MyValidationService myValidationService) {
this.myService = service;
this.myValidationService = myValidationService;
}
@PostMapping(path = "/users", produces = "application/json", consumes =
"application/json")
public ResponseEntity<User> getUserList(@Valid @RequestBody final RequestPayload
requestPayload, @RequestHeader Map<String, String> headers) throws MyException {
// check the credentials and permission
Map<String, String> credInfo = myValidationService.validateHeaders(headers);
// process payload
return myService.retrieveUsers(requestPayload);
}
}
测试如下:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc
class MyControllerTest {
@MockBean
private MyService myService;
@MockBean
private MyValidationService myValidationService;
@Autowired
private MockMvc mockMvc;
@Autowired
MyController myController;
@Test
public void contextLoads() throws Exception {
Assert.assertNotNull(myController);
}
@Test
void getUserList() throws Exception {
List<User> users = returnUserList();
HttpEntity<RequestPayload> requestHttpEntity = new HttpEntity<>(returnPayload(), null);
when(myService.retrieveUsers(any(RequestPayload.class))).thenReturn(users);
mockMvc.perform(post("/integrations/users")
.contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(returnPayload()))
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().is2xxSuccessful());
}
}
我得到的回应是:
MockHttpServletResponse:
Status = 404
Error message = null
Headers = []
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
【问题讨论】:
-
当你正常启动spring boot应用程序时,这个端点是否工作?
-
是的,正常运行。
-
@Deadpool 我们在同一页面上。试过了,结果一样。
-
@Deadpool 我会尝试把一些东西放在一起。我基本上简化了真实的代码。我刚刚还更新了 junit5-jupiter 和 mockito 的版本。将第二行改为
@ExtendWith(MockitoExtension.class) @RunWith(JUnitPlatform.class) -
不。没变。在黑暗中拍摄!
标签: java spring spring-boot junit5