有没有更新的 Spring AOP 和 mockito 方法? [英] Is there a newer approach to Spring AOP and mockito?
本文介绍了有没有更新的 Spring AOP 和 mockito 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 Spring AOP 方面无法使用 Mockito.此线程已超过 6 年.
I have managed to solve a problem with Spring-boot aop and mocking test services using an approach detailed in Spring AOP Aspect not working using Mockito. This thread is over 6 years old.
有没有更新的方法?
编辑从我的具体实现中添加更多细节.
EDIT adding more detail from my specific implementation.
控制器:
@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);
}
}
在我的测试课上,我有:
In my test class, I have:
@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
始终为空.
It fails and throws a NullPointerException. When debugging, the endpointService
is always null.
有什么想法吗?
推荐答案
您现在可以使用注解@MockBean.这是春季测试中某种包装好的模拟.
You can use the annotation @MockBean now. It's some sort of wrapped mockito in spring testing.
@RunWith(SpringRunner.class)
public class ExampleTests {
@MockBean
private ExampleService service;
@Autowired
private UserOfService userOfService;
@Test
public void testUserOfService() {
given(this.service.greet()).willReturn("Hello");
String actual = this.userOfService.makeUse();
assertEquals("Was: Hello", actual);
}
@Configuration
@Import(UserOfService.class) // A @Component injected with ExampleService
static class Config {
}
}
这篇关于有没有更新的 Spring AOP 和 mockito 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文