Reputation: 51
I was wondering what I am doing wrong when testing my aspect functionality. The aspect is working in production (passed testing by QA), but I am trying to get my integration unit test to pass. 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 just returns a list of all users, but when the aspect is used it restricts what users are shown.
@Repository
UsersDaoImpl implements UsersDao {
...
}
And my UsersService:
@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've also added the xml confguration:
context:annotation-config></context:annotation-config>
<aop:aspectj-autoproxy proxy-target-class="true"/>
<context:component-scan base-package="com.example.aspect" />
Can anyone advise what I am doing wrong?
Upvotes: 5
Views: 2956
Reputation: 41261
From what I can see of your test, it ought to work - so you have some tweaking to do regarding classpath scanning, ensuring the test is using the 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 test method.
You could also run your test in a debugger - add a breakpoint in your test class, and check what class usersDao
is at runtime.
Upvotes: 1