Skip to content

Instantly share code, notes, and snippets.

@benelog
Created January 17, 2012 07:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benelog/1625374 to your computer and use it in GitHub Desktop.
Save benelog/1625374 to your computer and use it in GitHub Desktop.
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