Spring AOP建议不应用于单元测试。在正常执行和集成测试期间,一切似乎都运行良好,但在运行单元测试时未应用。
对 Spring 来说相对较新,并且与这个问题斗争了一段时间。看起来像一些配置问题。尝试了不同类型的跑步者,但没有任何运气。还尝试与AspectJWeaver集成以进行编译时编织,但在遗留代码库中遇到了许多编译问题,我退后一步。
单元测试
@RunWith(SpringRunner.class)
@SpringBootTest
@EnableAspectJAutoProxy
public class UserServiceImpl
private UserServiceImpl userServiceSpy;
@Mock
private UserDao userDao;
@Mock
private MembershipDao membershipDao;
@Mock
private Service1 service1;
@Mock
private Service2 service2;
@Mock
private TroubleshootingLogService troubleshootingLogService;
@Before
public void setup() {
UserServiceImpl userService = new UserServiceImpl(userDao, membershipDao,service1, service2, <param1>, <param2>);
userServiceSpy = spy(userService)
// some other variables inits...
}
// All the unit tests.
集成测试
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestExecutionListeners(value = {FlywayTestExecutionListener.class}, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS)
@FlywayTest
@ActiveProfiles("local")
public class UserServiceIntegrationTest {
@ClassRule
public static final WireMockClassRule wireMockRule = new WireMockClassRule(wireMockConfig().dynamicPort());
@Autowire
private UserDao userDao;
@Autowire
private MembershipDao membershipDao;
@Autowire
private Service1 service1;
@Autowire
private Service2 service2;
@Before
public void init(){
//clean up persisted test states
}
// All integration tests
}
方面
@Aspect
@Component
@Order(1)
public class UserExceptionLoggingAdvisor extends AbstractExceptionLoggingAdvisor {
private static final Logger LOGGER = LoggerFactory.getLogger(UserExceptionLoggingAdvisor.class);
@Around("@annotation(LogException) && args(directoryId, userId, userToUpdate)")
public Object handleException(ProceedingJoinPoint joinPoint, String directoryId, String userId, ExternalUser userToUpdate) throws Throwable {
LOGGER.debug("Advising execution to handle possible ScimException");
}
当我们在 Aspect 类上有一个断点时,在private static final Logger LOGGER = LoggerFactory.getLogger(UserExceptionLoggingAdvisor.class);
行处,单元测试中断。但是,当它用于集成测试时,它不会中断单元测试的实际@Around建议。
谁能建议我如何解决这个问题。
"配置问题">
因为你没有透露你是如何调用你的单元测试的,也没有一个类。我的猜测是它不会触发,因为您已将完全限定的名称表达到LogException
注释中。
应该是my.full.packagename.logexception
我的建议是保持你的"单元测试"尽可能简单,并放弃让方面在你的单元测试中工作的想法。
太多的嘲笑从来都不是一件好事,在马桶上测试:不要过度使用模拟