问题
I have an aspect class as below -
public class TestAspect {
@AfterThrowing(pointcut = "execution(* *(..)) ", throwing = "testException")
public void afterThrowAdvice(TestException testException) throws Exception {
}
}
Now anytime any class throws TestException, TestAspect's afterThrowAdvice method is getting called. From Unit tests as well without using any spring configuration xmls, running as a plain junit test. How do I mock to not do anything when that method is called? I tried in my unit test the below but it won't work. Rightly so because the aspect is not autowired into the classes I am testing. Any suggestions? -
@Mock
private TestAspect testAspect
doNothing.when(testAspect).afterThrowAdvice(any(TestException.class));
回答1:
One way to achieve this is using @Profile
option .
Following profile configuration will make sure the aspect bean is only available with the profile is not test
@Component
@Aspect
@Profile("!test")
public class TestAspect {
@AfterThrowing(pointcut = "execution(* *(..)) ", throwing = "testException")
public void afterThrowAdvice(TestException testException) throws Exception {
...
}
}
and following Junit testcase runs the the tests with profile as test
and no aspect bean is created here
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestExConfig.class)
@ActiveProfiles("test")
public class TestService{
@Autowired
ServiceWithException service;
@Test(expected = TestException.class)
public void testExceptionMethod() throws TestException {
service.testMethod();
}
}
Hope this helps
来源:https://stackoverflow.com/questions/60893258/mocking-an-aspect-class-invoked-after-an-exception-is-thrown-in-junit