1@RunWith(SpringJUnit4ClassRunner.class)
2@SpringApplicationConfiguration(Config.class)
3public class AspectTesting {
4
5 @Autowired
6 ServiceWithAspect service;
7
8 @Autowired
9 Verifier verifyingAspect;
10
11 @Test
12 public void test() {
13 // given
14 boolean condition = false;
15
16 // when
17 try {
18 service.doit();
19 } catch (Exception swallow) {}
20
21 // then
22 try {
23 condition = ((VerifyingAspect) ((Advised) verifyingAspect).getTargetSource().getTarget()).wasExecuted();
24 } catch (Exception swallow) {}
25
26 // then
27 Assert.assertTrue(condition);
28 }
29}
30
31@Configuration
32@EnableAspectJAutoProxy
33@ComponentScan("aspects")
34class Config {
35}
36
37@Component
38class VerifyingAspect implements Verifier {
39
40 private boolean executed = false;
41
42 public boolean wasExecuted() {
43 return executed;
44 }
45
46 @Override
47 public void invoked() {
48 executed = true;
49 }
50}
51
52@Service
53class ServiceWithAspect {
54 public void doit() {
55 throw new RuntimeException();
56 }
57}
58
59@Component
60@Aspect
61class TestedAspect {
62
63 @Autowired
64 Verifier verifier;
65
66 @AfterThrowing(pointcut = "execution(* *(..))", throwing = "exception")
67 public void afterThrowingAdvice(Exception exception) {
68 // your aspect logic here
69 verifier.invoked();
70 }
71}
72
73interface Verifier {
74 void invoked();
75}