Mocking an Aspect class invoked after an exception is thrown in Junit

為{幸葍}努か 提交于 2021-02-11 17:42:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!