I want to test a class with cross-business processing created by Spring AOP as a single unit.
Spring AOP is established based on DI, and the side that uses the component injects a proxy (not the bean itself registered in the container, but the extension of the function defined in AOP for that bean) instance. AOP is realized by.
However, since I want to do unit testing this time, I would like to provide a method for testing without starting the DI container and depending on the context.
If there is null
in the argument, implement the process of throwing NullPointerException
in AOP and apply it to the method of TestService
(test class) class. (The NullCheck annotation is just a marker, so I'll omit it here.)
AspectLogic.java
@Aspect
@Component
public class AspectLogic {
@Around("@annotation(NullCheck)")
public Object invoke(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("NullCheck!!");
Stream.of(proceedingJoinPoint.getArgs()).forEach(Objects::requireNonNull);//Get all arguments and Objects::Check with requireNonNull
return proceedingJoinPoint.proceed();
}
}
TestService.java
public class TestService {
@NullCheck
public void doSomething(Object arg) {
}
}
Let's implement the part where Spring DI gets proxy from Bean by ourselves. ʻ Instance of AspectJProxyFactory Add the Aspect class created this time to. If you hit the test sample method using the proxy obtained from the factory, it seems that you can confirm that the process defined in AOP is called and
NullPointerException` is thrown.
TestAspectLogic.java
public class TestAspectLogic {
@Test
public void testAspect() {
AspectJProxyFactory factory = new AspectJProxyFactory(new TestService());
factory.addAspect(new AspectLogic()); //Apply AspectLogic class here
TestService proxy = factory.getProxy();
try {
proxy.doSomething(null);
failBecauseExceptionWasNotThrown(NullPointerException.class);
} catch(NullPointerException npe) {
}
}
}
output
NullCheck!!
Write a test for AOP as well.
Recommended Posts