什么是对Spring Security注释@PostFilter
和@PreFilter
进行单元测试的正确方法。
我在DAO类中使用以下注释:
TodoDao.java
@Component
@Transactional
public class TodoDao implements ITodoDao {
@Autowired
private SessionFactory sessionFactory;
@Autowired
private AuthenticationFacade authenticationFacade;
@Override
@PostFilter("filterObject.userByUserId == @authenticationFacade.getAuthenticatedFacade()")
public List<Todo> getTodosByUserId(int userId) {
return sessionFactory.getCurrentSession().createQuery("from Todo where userId = ?").setParameter(0, userId).list();
}
}
这是我的AuthenticationFacade类:
AuthenticationFacade.java
@Component
public class AuthenticationFacade implements IAuthenticationFacade {
@Autowired
private IUserDao IUserDao;
public Authentication getAuthentication() {
return SecurityContextHolder.getContext().getAuthentication();
}
public User getAuthenticatedFacade() {
Authentication authentication = getAuthentication();
User user = IUserDao.findByUsername(authentication.getName());
return user;
}
}
这是我的DAO单元测试课程,我使用H2内存数据库:
TodoDaoTest.java
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration (value = "classpath:/conf/applicationContext-test.xml")
@Transactional
public class TodoDaoTest {
@Autowired
SessionFactory testSessionFactory;
@InjectMocks
TodoDao todoDao;
private boolean mockInitialized = false;
@Before
public void setUp(){
if(!mockInitialized) {
MockitoAnnotations.initMocks(this);
mockInitialized = true;
}
todoDao.setSessionFactory(testSessionFactory);
}
@Test
@WithMockUser (username = "user", roles = "ROLE_USER")
//I want to test here if @WithMokUser is different from userId
//Than the list sould return empty always.
public void getTodosByUserIdShouldReturnEmptyListIfCurrentUserIsDifferentFromSearchedUser(){
int userId = 3;
assertTrue(todoDao.getTodosByUserId(userId).isEmpty());
}
}