说我有这个资源:Shiro:如何为使用@RequiresRoles保护的端点编写测试?
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@Path("/authhello")
@Api(value = "hello", description = "Simple endpoints for testing api authentification",
hidden = true)
@Produces(MediaType.APPLICATION_JSON)
@RequiresAuthentication
public class AuthenticatedHelloWorldResource {
private static final String READ = "READ";
private static final String WRITE = "WRITE";
@GET
@ApiOperation(value = "helloworld",
notes = "Simple hello world.",
response = String.class)
@RequiresRoles(READ)
public Response helloWorld() {
String hello = "Hello world!";
return Response.status(Response.Status.OK).entity(hello).build();
}
@GET
@Path("/{param}")
@ApiOperation(value = "helloReply",
notes = "Returns Hello you! and {param}",
response = String.class)
@RequiresRoles(WRITE)
public Response getMsg(@PathParam("param") String msg) {
String output = "Hello you! " + msg;
return Response.status(Response.Status.OK).entity(output).build();
}
}
我应该写确认测试,某些(测试)用户从端点的响应,并且某些用户不?如果是这样的话:我该如何编写这些测试?我已经试过这样的事情:
import javax.ws.rs.core.Application;
import org.glassfish.jersey.server.ResourceConfig;
import org.junit.Test;
import com.cognite.api.shiro.AbstractShiroTest;
import static org.junit.Assert.assertEquals;
public class AuthenticatedHelloWorldTest extends AbstractShiroTest {
@Override
protected Application configure() {
return new ResourceConfig(AuthenticatedHelloWorldResource.class);
}
@Test
public void testAuthenticatedReadHelloWorld() {
final String hello = target("/authhello").request().get(String.class);
assertEquals("Hello world!", hello);
}
@Test
public void testAuthenticatedWriteHelloWorld() {
final String hello = target("/authhello/test").request().get(String.class);
assertEquals("Hello you! test", hello);
}
}
,但我不知道如何实际测试@RequiresRoles
-annotation的功能。我已阅读Shiro's page on testing,但我无法写出失败的测试(例如,对没有WRITE
角色的主题尝试访问/authhello/test
)的测试。任何提示将不胜感激。
谢谢你花时间回答。经过一番认真的挖掘和阅读之后,我意识到我正如你所说,错过了一些设置代码。我设法在我的测试中复制了在应用程序中完成的设置(尽管很遗憾,我无法在此分享示例)。 – L42