有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java SpringBoot2:测试运行期间AspectJ的问题

我有一个小AspectJ类的项目:

package com.blabla.joy.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class SomeAspect {
    public SomeAspect() {

    }
}

还有一个小的测试类:

package com.blabla.joy.aspect;

import com.blabla.joy.MainSpringBoot;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = {MainSpringBoot.class})
public class SomeTest {

    @MockBean
    private SomeAspect someAspect;

    @Test
    public void someTest(){
        //test something
    }
}

主要的应用程序类别是:

package com.blabla.joy;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@SpringBootApplication(exclude = MultipartAutoConfiguration.class)
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class MainSpringBoot implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(MainSpringBoot.class, args);
    }

    @Override
    public void run(String... arg0) throws Exception {
        System.out.println("i'm running!!!");
    }
}

当我运行某个测试时,出现以下错误:

java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mainSpringBoot': BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: [com.blabla.joy.aspect.SomeAspect$MockitoMock$2005048991] cannot extend concrete aspect [com.blabla.joy.aspect.SomeAspect]
...
Caused by: org.springframework.aop.framework.AopConfigException: [com.blabla.joy.aspect.SomeAspect$MockitoMock$2005048991] cannot extend concrete aspect [com.blabla.joy.aspect.SomeAspect]
...

这是什么意思?我应该在aspect、test或main类中添加一些特殊的逻辑(注释等)

附言:我在项目中使用SpringBoot2


共 (1) 个答案

  1. # 1 楼答案

    试试这个:

    @RunWith(SpringRunner.class)
    @SpringBootTest
    @ContextConfiguration(classes = {MainSpringBoot.class})
    public class SomeTest {
    
        @Autowired
        @InjectMocks
        private SomeAspect someAspect;
    
        @Before
        public void init(){
            MockitoAnnotations.initMocks(this)
        }
    
        @Test
        public void someTest(){
            //test something
        }
    }