在 quarkus 中测试时验证模拟用户
authenticating mock user when testing in quarkus
我正在尝试测试受@RolesAllowed
保护的quarkus rest-endpoint
...
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@RolesAllowed({ "APPLICATION_USER"})
public Response getFile(@PathParam(value = "id") String documentId, @Context UriInfo uriInfo)
...
测试用例
@QuarkusTest
class DocumentResourceTest {
@Test
public void testDocumentEndpoint() {
String documentId = "someId";
given()
.when().get("/documents/" + documentId)
.then()
.statusCode(200);
}
}
如何为我的测试用例模拟角色为 'APPLICATION_USER' 的经过身份验证的用户?
您可以注入一个 SecurityIdentity
,然后您可以使用 Mockito 将相关角色存根:
@QuarkusTest
public class DocumentResourceTest {
@InjectMock
SecurityIdentity identity;
@BeforeEach
public void setup() {
Mockito.when(identity.hasRole("APPLICATION_USER")).thenReturn(true);
}
@Test
public void testDocumentEndpoint() {
String documentId = "someId";
given()
.when().get("/documents/" + documentId)
.then()
.statusCode(200);
}
}
如果您想测试各种不同的角色,您当然可以将存根调用移动到您的个人测试中。
请注意,您需要添加 quarkus-junit5-mockito
依赖项才能正常工作:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5-mockito</artifactId>
<scope>test</scope>
</dependency>
除了已接受的答案外,还有本指南解释了如何处理集成测试:https://quarkus.io/guides/security-oauth2#integration-testing
第一句是:
If you don’t want to use a real OAuth2 authorization server for your integration tests, you can use the Properties based security extension for your test, or mock an authorization server using Wiremock.
所以我认为基于 属性 的安全扩展也适用于您:https://quarkus.io/guides/security-properties
我正在尝试测试受@RolesAllowed
保护的quarkus rest-endpoint...
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@RolesAllowed({ "APPLICATION_USER"})
public Response getFile(@PathParam(value = "id") String documentId, @Context UriInfo uriInfo)
...
测试用例
@QuarkusTest
class DocumentResourceTest {
@Test
public void testDocumentEndpoint() {
String documentId = "someId";
given()
.when().get("/documents/" + documentId)
.then()
.statusCode(200);
}
}
如何为我的测试用例模拟角色为 'APPLICATION_USER' 的经过身份验证的用户?
您可以注入一个 SecurityIdentity
,然后您可以使用 Mockito 将相关角色存根:
@QuarkusTest
public class DocumentResourceTest {
@InjectMock
SecurityIdentity identity;
@BeforeEach
public void setup() {
Mockito.when(identity.hasRole("APPLICATION_USER")).thenReturn(true);
}
@Test
public void testDocumentEndpoint() {
String documentId = "someId";
given()
.when().get("/documents/" + documentId)
.then()
.statusCode(200);
}
}
如果您想测试各种不同的角色,您当然可以将存根调用移动到您的个人测试中。
请注意,您需要添加 quarkus-junit5-mockito
依赖项才能正常工作:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5-mockito</artifactId>
<scope>test</scope>
</dependency>
除了已接受的答案外,还有本指南解释了如何处理集成测试:https://quarkus.io/guides/security-oauth2#integration-testing
第一句是:
If you don’t want to use a real OAuth2 authorization server for your integration tests, you can use the Properties based security extension for your test, or mock an authorization server using Wiremock.
所以我认为基于 属性 的安全扩展也适用于您:https://quarkus.io/guides/security-properties