在Spring中编写方面功能的集成测试

时间:2017-04-11 15:40:33

标签: java spring junit spring-aop aspect

我想知道在测试我的方面功能时我做错了什么。该方面正在生产(通过QA测试),但我试图让我的集成单元测试通过。这是我的代码:

@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();
}

我的DAO方法只返回所有用户的列表,但是当使用方面时,它会限制用户的显示内容。

@Repository
UsersDaoImpl implements UsersDao {
  ...
}

我的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);
  }
}

在我的单元测试中,我正在执行以下操作:

@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);
}

我还添加了xml配置:

context:annotation-config></context:annotation-config>
<aop:aspectj-autoproxy proxy-target-class="true"/>

<context:component-scan base-package="com.example.aspect" />

有人可以告诉我做错了吗?

1 个答案:

答案 0 :(得分:1)

从我所看到的测试中,它应该可以工作 - 所以你需要做一些关于类路径扫描的调整,确保测试使用预期的配置等。

我建议暂时添加:

 @Autowired
 ApplicationContext context;

 @Before
 public void dumpBeans() {
      System.out.println(context.getBeansOfType(UsersDao.class));
 }

或者更简单地说,在测试方法中System.out.println(usersDao.getClass())

您还可以在调试器中运行测试 - 在测试类中添加断点,并检查运行时类usersDao