Reputation: 845
I'm trying to test a quarkus rest-endpoint which is secured with @RolesAllowed
...
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@RolesAllowed({ "APPLICATION_USER"})
public Response getFile(@PathParam(value = "id") String documentId, @Context UriInfo uriInfo)
...
The test case
@QuarkusTest
class DocumentResourceTest {
@Test
public void testDocumentEndpoint() {
String documentId = "someId";
given()
.when().get("/documents/" + documentId)
.then()
.statusCode(200);
}
}
How can i mock an authenticated user with role 'APPLICATION_USER' for my test case ?
Upvotes: 4
Views: 2954
Reputation: 15145
A more convinient way to mock the security is to use Quarkus' security testing features:
https://quarkus.io/guides/security-testing#testing-security
Including
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-test-security</artifactId>
<scope>test</scope>
</dependency>
allows you to write
@Test
@TestSecurity(authorizationEnabled = false)
void someTestMethod() {
...
}
@Test
@TestSecurity(user = "testUser", roles = {"admin", "user"})
void otherTestMethod() {
...
}
Upvotes: 5
Reputation: 43
In addition to the accepted answer, there is also this guide which explains how to deal with integration tests: https://quarkus.io/guides/security-oauth2#integration-testing
The first sentence there is:
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.
So I think the property based security extension could also work for you: https://quarkus.io/guides/security-properties
Upvotes: 0
Reputation: 72304
You can inject a SecurityIdentity
which you can then stub out with the relevant role using 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);
}
}
You can of course move the stubbing call to your individual tests if you want to test a variety of different roles.
Note that you'll need to add the quarkus-junit5-mockito
dependency for this to work:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5-mockito</artifactId>
<scope>test</scope>
</dependency>
Upvotes: 9