Java 使用MockMvc进行Spring Boot Aspectj测试
我有一个Aspectj的Spring启动代码。这段代码是用基本的MVC架构编写的。然后我试着用MockMVC测试它。但是当我尝试测试它时,Aspectj并没有中断。Aspectj有特殊的配置吗 控制器:Java 使用MockMvc进行Spring Boot Aspectj测试,java,spring-boot,aspectj,spring-boot-test,Java,Spring Boot,Aspectj,Spring Boot Test,我有一个Aspectj的Spring启动代码。这段代码是用基本的MVC架构编写的。然后我试着用MockMVC测试它。但是当我尝试测试它时,Aspectj并没有中断。Aspectj有特殊的配置吗 控制器: @GetMapping("user/{userId}/todo-list") public ResponseEntity<?> getWaitingItems(@RequestUser CurrentUser currentUser){ ...handle it with s
@GetMapping("user/{userId}/todo-list")
public ResponseEntity<?> getWaitingItems(@RequestUser CurrentUser currentUser){
...handle it with service method.
}
测试:
Spring将只实例化web层,而不会加载完整的应用程序上下文
但是,在这个测试中,Spring Boot只实例化web层,而不是整个上下文。
为了测试Aspectj,您需要使用@SpringBootTest注释加载整个应用程序上下文
@SpringBootTest
@ActiveProfiles("test")
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
public class ControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Autowired
private Controller controller;
@Before
public void setUp() {
mockMvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.build();
}
@Test
public void getWaitingItems() throws Exception {
mockMvc.perform(get("/user/{userId}/todo-list", 1L))
.andExpect(status().isOk());
}
}
@SpringBootTest注释告诉Spring Boot查找主配置类(例如带有@SpringBootApplication的配置类),并使用该配置类启动Spring应用程序上下文
因此,使用@SpringBootTest
注释对测试进行注释
@SpringBootTest
@ActiveProfiles("test")
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
public class ControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Autowired
private Controller controller;
@Before
public void setUp() {
mockMvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext)
.build();
}
@Test
public void getWaitingItems() throws Exception {
mockMvc.perform(get("/user/{userId}/todo-list", 1L))
.andExpect(status().isOk());
}
}
如果您想对特定控制器(web层)+自定义方面逻辑(AOP层)进行集成测试,则不需要
@SpringBootTest
试试这样的
@WebMvcTest(controllers = {AnyController.class})
@Import({AopAutoConfiguration.class, ExceptionAspect.class})
public class ErrorControllerAdviceTest {
- AnyController.class:正在测试的控制器
- AopAutoConfiguration.class:AOP的Spring引导自动配置
- ExceptionAspect.class:包含AOP逻辑的类
我不确定我的解决方案在技术上是否与@Deadpool answers相同,谢谢。与实例化整个应用程序上下文相比,执行时间更短,尤其是当您必须测试来自不同控制器的数十个端点时。IMHO,这应该被投票表决,因为这是更好的答案。
@WebMvcTest(controllers = {AnyController.class})
@Import({AopAutoConfiguration.class, ExceptionAspect.class})
public class ErrorControllerAdviceTest {
@Aspect
@Component
public class ExceptionAspect {}