我已经设法解决了一个问题,与 Spring 启动aop和模拟测试服务使用的方法在Spring AOP Aspect not working using Mockito中详细说明。
有没有新的方法?
- 编辑**从我的具体实施中添加更多详细信息。
控制器:
@RestController
public class EndpointController {
private EndpointService endpointService;
@Autowired
public EndpointController(EndpointService endpointService) {
this.endpointService = endpointService;
}
@PostMapping(path = "/endpoint", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
private @ResponseBody EndpointResponse doSomething(/* ... */, @RequestBody SomeObject someObject) throws Exception {
return endpointService.doSomething(someObject);
}
}
在我的测试类中,我有:
@RunWith(SpringRunner.class)
public class EndpointControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void shouldBeSuccessfulAccessingTheEndpoint() throws Exception {
SomeObject someObject = new SomeObject(/* values */);
ObjectMapper mapper = new ObjectMapper();
String payload = mapper.writeValueAsString(someObject);
mockMvc.perform(post("/endpoint").contentType(MediaType.APPLICTION_JSON).content(payload)).andExpect(status().isOK));
}
}
失败,抛出NullPointerException异常,调试时endpointService
始终为空。
有什么想法吗?
1条答案
按热度按时间luaexgnf1#
现在可以使用注解@MockBean,它是 Spring 测试中的某种 Package mockito。
https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/mock/mockito/MockBean.html