Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AspectJ expression Test with Spring 3.1
package edu.tdd.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class LogAspect {
private LogRepository repository;
public LogAspect(LogRepository repository){
this.repository = repository;
}
@Before("execution(void *.run())")
public void log(JoinPoint jp){
String message = jp.getKind() + ":" + jp.getSignature().getName();
repository.insertLog(message);
}
}
package edu.tdd.aop;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
public class LogAspectTest {
@Autowired Runnable targetProxy;
@Autowired LogRepository repository;
@Test
public void proxyCreated() {
assertTrue(AopUtils.isAopProxy(targetProxy));
}
@Test
public void logInserted() {
targetProxy.run();
verify(repository).insertLog("method-execution:run");
}
@Configuration
@EnableAspectJAutoProxy
static public class TestContext {
@Bean LogAspect aspect() {
return new LogAspect(repository());
}
@Bean LogRepository repository(){
return mock(LogRepository.class);
}
@Bean Runnable target(){
return new Printer();
}
}
}
package edu.tdd.aop;
public class LogRepository {
public void insertLog(String message) {
System.out.println(message);
}
}
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.8</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>2.2</version>
</dependency>
package edu.tdd.aop;
public class Printer implements Runnable{
@Override
public void run() {
System.out.println("hello!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.