(首先,我道歉,我的代码不能超过一个级别的缩进)
我正在尝试编写单元测试来测试我的服务层方法。这些服务类的接口使用@Preauthorize注释:
public interface LocationService {
void setLocationRepository(LocationRepository locationRepository);
/**
* Get all Location objects from the backend repository
* @return
*/
@PreAuthorize("has_role('ROLE_ADMIN')")
List<Location> getAll();
单元测试看起来像这样:
@Before
public void setUp() {
admin = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("admin", "admin"));
user = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("user", "user"));
// create Mock Repository
// set up the actual service WITH the repository
locationService = new LocationServiceImpl();
locationService.setLocationRepository(locationRepository);
}
@Test(expected = AccessDeniedException.class)
@SuppressWarnings("unused")
public void testGetAllAsUser() {
SecurityContextHolder.getContext().setAuthentication(user);
List<Location> resultList = locationService.getAll();
}
最后,这是我的applicationContext.xml的安全上下文:
<!-- Temporary security config. This will get moved to a separate context
file, but I need it for unit testing right now -->
<security:http use-expressions="true">
<security:form-login />
<security:session-management
invalid-session-url="/timeout.jsp">
<security:concurrency-control
max-sessions="1" error-if-maximum-exceeded="true" />
</security:session-management>
</security:http>
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider>
<security:password-encoder hash="plaintext" />
<security:user-service>
<security:user name="admin" password="admin"
authorities="ROLE_ADMIN" />
<security:user name="user" password="user"
authorities="ROLE_USER" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
<security:global-method-security
pre-post-annotations="enabled" proxy-target-class="true" />
不幸的是,正在忽略@PreAuthorize标记,允许有ROLE_USER的人运行getAll()。
有人可以帮忙吗?
杰森
答案 0 :(得分:1)
该行:
locationService = new LocationServiceImpl();
创建一个新的位置服务,完全绕过spring。如果你使用的是spring junit runner,你应该使用@Resource来注入locationService,这样你就可以使用spring bean而不仅仅是你的pojo。