在我正在开发的项目中,我们使用OpenEJB作为测试EJB的框架。我们以编程方式构造InitialContext
,并使用它来获取事务管理器和各种EJB。
但是,我现在必须测试的EJB有@RolesAllowed
注释,因此OpenEJB拒绝获取该EJB,认为我没有所需的权限。
如何向OpenEJB指定此测试应该模拟的用户,以及与他相关的角色?
答案 0 :(得分:5)
@RunAs
建议bkail提及绝对是一个很好的方法。第二种不涉及内部类的方法是登录测试用例。
当您引导OpenEJB时,请在InitialContext
属性中指定用户/传递,如下所示:
public void testAsManager() throws Exception {
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.LocalInitialContextFactory");
p.put(Context.SECURITY_PRINCIPAL, "jane");
p.put(Context.SECURITY_CREDENTIALS, "waterfall");
InitialContext context = new InitialContext(p);
try {
movies.addMovie(new Movie("Quentin Tarantino", "Reservoir Dogs", 1992));
movies.addMovie(new Movie("Joel Coen", "Fargo", 1996));
movies.addMovie(new Movie("Joel Coen", "The Big Lebowski", 1998));
List<Movie> list = movies.getMovies();
assertEquals("List.size()", 3, list.size());
for (Movie movie : list) {
movies.deleteMovie(movie);
}
assertEquals("Movies.getMovies()", 0, movies.getMovies().size());
} finally {
context.close();
}
}
然后可能再次作为不同的用户进行测试:
public void testAsEmployee() throws Exception {
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.LocalInitialContextFactory");
p.put(Context.SECURITY_PRINCIPAL, "joe");
p.put(Context.SECURITY_CREDENTIALS, "cool");
InitialContext context = new InitialContext(p);
try {
movies.addMovie(new Movie("Quentin Tarantino", "Reservoir Dogs", 1992));
movies.addMovie(new Movie("Joel Coen", "Fargo", 1996));
movies.addMovie(new Movie("Joel Coen", "The Big Lebowski", 1998));
List<Movie> list = movies.getMovies();
assertEquals("List.size()", 3, list.size());
for (Movie movie : list) {
try {
movies.deleteMovie(movie);
fail("Employees should not be allowed to delete");
} catch (EJBAccessException e) {
// Good, Employees cannot delete things
}
}
// The list should still be three movies long
assertEquals("Movies.getMovies()", 3, movies.getMovies().size());
} finally {
context.close();
}
}
您可以通过将users.properties
和groups.properties
文件放在测试用例的类路径中来配置测试用户和组。在maven中,它位于以下位置:
users.properties
文件可能如下所示
joe=cool
jane=waterfall
groups.properties
就像这样
Manager=jane
Employee=jane,joe
答案 1 :(得分:1)
请参阅OpenEJB Testing Security Example。基本上,你是间接通过没有@RolesAllowed的测试bean,但在调用第二个bean之前使用@RunAs来切换角色。