Reputation: 11
I'd like to run a parametrized test in Spock using the @WithMockUser with a different role per each iteration.
As an example, the following test code shows no compilation error and is run twice. But the result fails, since the #role is resolved only in the @Unroll, but not in the @WithMockUser annotation.
@Unroll("#role is authorized to get admin")
@WithMockUser(username = "user", roles = ["#role"])
def "User is authorized to get admin"() {
when:
def adminDto = adminController.getAdmin()
then:
adminDto.getStatusCode() == HttpStatus.OK
where:
role << ["USER", "ADMIN"]
}
So my question is: Is it possible to run such a test as a parametrized one?
Thank you in advance!
Note: I'm aware the annotation could look like:
@WithMockUser(username = "user", roles = ["USER", "ADMIN"])
but this would be a different behavior - one call with both roles.
Upvotes: 1
Views: 838
Reputation: 13222
Short answer no.
The annotations are statically compiled at compile time and cannot be modified by Spock, the iterations are generated/evaluated dynamically at runtime.
The @Unroll
annotation has some special support for data variables to make it work, while the Spring annotation doesn't know anything about Spock.
You could look at WithMockUserSecurityContextFactory and use that to manually set the the SecurityContext
in the given
block.
Upvotes: 1