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建议,而对于集成测试,它却没有违反。
有人可以建议我如何解决此问题。
答案 0 :(得分:0)
这不是“配置问题”
由于您尚未公开如何调用单元测试,因此没有公开任何类。我的猜测是,由于您已经在LogException
注释中表达了完全限定的名称,因此不会触发它。
应为my.full.packagename.logexception
我的建议是使您的“单元测试”尽可能简单,并放弃让Aspects在单元测试中工作的想法。
太多的嘲笑从来都不是一件好事, Testing on the Toilet: Don’t Overuse Mocks