Writing an integration test for aspect functionality in Spring
I was wondering what I was doing wrong when I test my functionality. Aspect is working in production (passed QA testing) but I am trying to pipe my integration to a unit test. Here is my code:
@Aspect
@Component
public class MyAspect {
@Pointcut("execution(* com.example.dao.UsersDao(..)) && args(.., restrictions)")
protected void allUsersPointcut(List<String> restrictions) {
}
@Around("allUsersPointcut(restrictions)")
public Object applyUserRestrictions(final ProceedingJoinPoint pjp, List<String> restrictions) throws Throwable {
String restrict = "Jack";
restrictions.add(restrict);
return pjp.proceed();
}
My DAO method returns a list of all users, but when using aspect it restricts the display of users.
@Repository
UsersDaoImpl implements UsersDao {
...
}
And my UserService:
@Service
public class UsersService implements UsersService {
@Autowired
protected UsersDAO usersDAO;
...
@Transactional(readOnly=true)
public List<String> findUsers(List<String> restrictions) {
return this.usersDAO.findUsers(restrictions);
}
}
In my unit test, I am doing the following:
@RunWith(SpringJUnit4ClassRunner.class)
public class UserTest {
@Autowired
UsersService usersService;
@Test
public void testAspect() {
List<String> restrictions = null;
List<String> users = this.usersService.findUsers(restrictions);
Assert.notNull(users);
}
I also added the xml config:
context:annotation-config></context:annotation-config>
<aop:aspectj-autoproxy proxy-target-class="true"/>
<context:component-scan base-package="com.example.aspect" />
Can anyone please advise what I am doing wrong?
source to share
From what I can see in your test, it should work - so you have some setup to validate the classpath so that validation uses expected configuration, etc.
I recommend temporarily adding:
@Autowired
ApplicationContext context;
@Before
public void dumpBeans() {
System.out.println(context.getBeansOfType(UsersDao.class));
}
Or, more simply, System.out.println(usersDao.getClass())
in the testing method.
You can also run your test in the debugger - add a breakpoint to your test class and check which class usersDao
is at runtime.
source to share