栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

JUnit如何测试@PreAuthorize批注及其由spring MVC控制器指定的spring EL?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JUnit如何测试@PreAuthorize批注及其由spring MVC控制器指定的spring EL?

由于您要测试通过Spring AOP实现的功能,因此需要使用Spring
TestContext
框架针对应用程序上下文运行测试。

然后,使用最少的安全性配置创建基本测试:

abstract-security-test.xml

<security:authentication-manager alias="authenticationManager">    <security:authentication-provider user-service-ref = "userService" /></security:authentication-manager><security:global-method-security pre-post-annotations="enabled" /><bean id = "userService" class = "..." />

AbstractSecurityTest.java

@ContextConfiguration("abstract-security-test.xml")abstract public class AbstractSecurityTest {    @Autowired    private AuthenticationManager am;    @After    public void clear() {        SecurityContextHolder.clearContext();    }    protected void login(String name, String password) {        Authentication auth = new UsernamePasswordAuthenticationToken(name, password);        SecurityContextHolder.getContext().setAuthentication(am.authenticate(auth));    }}

现在,您可以在测试中使用它:

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(...)public class CreatePostControllerSecurityTest extends AbstractSecurityTest {    ...    @Test    @ExpectedException(AuthenticationCredentialsNotFoundException.class)    public void testNoAuth() {        controller.modifyContent(...);    }    @Test    @ExpectedException(AccessDeniedException.class)    public void testAccessDenied() {        login("userWithoutAccessRight", "...");        controller.modifyContent(...);    }    @Test    public void testAuthOK() {        login("userWithAccessRight", "...");        controller.modifyContent(...);    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/484061.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号