Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing Spring @Around AOP methods

I can unit test most of my Spring classes without needing to do Spring "stuff".

I can unit test @Before advice methods without using Spring too:

Example code:

@Before("execution(* run(..)) && " + "" +           "target(target) && " +         "args(name)") public void logName(Object target, String name) {     logger.info("{} - run: {}", target, name); } 

Example test:

@Test public void testLogName() {     aspect.setLogger(mockLogger);     aspect.logName(this,"Barry");     assertTrue(mockLogger.hasLogged("TestAspect - run: Barry")); } 

However @Around advice deals with a ProceedingJoinPoint object:

@Around("com.xyz.myapp.SystemArchitecture.businessService()") public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {    // start stopwatch    Object retVal = pjp.proceed();    // stop stopwatch    return retVal;  } 

I don't know how to instantiate a ProceedingJoinPoint object. How do I test this class without starting a whole Spring application context?

like image 214
slim Avatar asked Jul 11 '12 15:07

slim


People also ask

What is the easiest method to write a unit test in spring?

Spring Boot simplifies unit testing with SpringRunner . It is also easier to write unit tests for REST Controller with MockMVC . For writing a unit test, Spring Boot Starter Test dependency should be added to your build configuration file (pom.

What is AOP spring?

What is Spring AOP? Spring AOP enables Aspect-Oriented Programming in spring applications. In AOP, aspects enable the modularization of concerns such as transaction management, logging or security that cut across multiple types and objects (often termed crosscutting concerns).

What is spring AOP example?

AOP is like triggers in programming languages such as Perl, . NET, Java, and others. Spring AOP module provides interceptors to intercept an application. For example, when a method is executed, you can add extra functionality before or after the method execution.

Is Springboottest a unit test?

No. A unit test is to test a single component in isolation. Using constructor injection in your beans allows you to very simply call new SomeService(myMock) , no Spring required.


1 Answers

You can test a Spring Aspect by creating a proxy programatically:

MyInterface target = new MyClass(); AspectJProxyFactory factory = new AspectJProxyFactory(target); MyAspect aspect = new MyAspect(arg); factory.addAspect(aspect); MyInterface proxy = factory.getProxy(); 

... then you can call methods on proxy, and make assertions about aspect, proxy and target.

like image 114
slim Avatar answered Oct 08 '22 03:10

slim