我有一个带有Aspectj的Spring引导代码。这个代码是用基本的MVC架构编写的。然后我就试着用MockMVC来测试它。但是当我试着测试它时,Aspectj并没有中断。有关于Aspectj的特殊配置吗?
主计长:
@GetMapping("user/{userId}/todo-list")
public ResponseEntity<?> getWaitingItems(@RequestUser CurrentUser currentUser){
...handle it with service method.
}方面:
@Pointcut("execution(* *(.., @RequestUser (*), ..))")
void annotatedMethod()
{
}
@Before("annotatedMethod() && @annotation(requestUser)")
public void adviseAnnotatedMethods(JoinPoint joinPoint, RequestUser requestUser)
{
...
}测试:
@WebMvcTest(value = {Controller.class, Aspect.class})
@ActiveProfiles("test")
@ContextConfiguration(classes = {Controller.class, Aspect.class})
@RunWith(SpringJUnit4ClassRunner.class)
public class ControllerTest
{
@Autowired
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Autowired
private Controller controller;
@MockBean
private Service service;
@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());
}
}发布于 2020-02-06 18:41:11
Spring @WebMvcTest只实例化web层,不会加载完整的应用程序上下文。
然而,在这个测试中,Spring只实例化了层,而没有实例化整个上下文.
为了测试Aspectj,需要使用@SpringBootTest注释加载整个应用程序上下文
@SpringBootTest注释告诉SpringBootTest查找一个主配置类(例如,一个带有@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());
}
}发布于 2020-03-15 21:44:51
如果您想要对特定控制器(web层)+自定义方面逻辑(AOP层)进行集成测试,则不需要使用@SpringBootTest。
试试像这样的东西
@WebMvcTest(controllers = {AnyController.class})
@Import({AopAutoConfiguration.class, ExceptionAspect.class})
public class ErrorControllerAdviceTest {@Aspect
@Component
public class ExceptionAspect {}使用SpringBoot2.2.1测试和JUNIT5。我不确定,我的解决方案在技术上是否和@Deadpool的答案一样
https://stackoverflow.com/questions/60101172
复制相似问题