Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

@WithMockUser doesn't work on method annotated as @BeforeEach #5067

Closed
AleksandrSl opened this issue Mar 3, 2018 · 2 comments
Closed

@WithMockUser doesn't work on method annotated as @BeforeEach #5067

AleksandrSl opened this issue Mar 3, 2018 · 2 comments

Comments

@AleksandrSl
Copy link

Summary

Strange behaviour of @WithMockUser on method annotated as @BeforeEach

Actual Behavior

@BeforeEach annotated method uses security context from @Test method that will be run after it

Expected Behavior

@BeforeEach should have security context specified in @WithMockUser annotation

Version

spring-boot-starter-security:2.0.0.RELEASE
(seems to be spring-security:5.0.3.RELEASE)

Sample

Full example

@BeforeEach
@WithMockUser(roles = ["ADMIN"])
fun setUp() {
    itemRepository.save(Item())
}

@Test
@Disabled
@WithMockUser(roles = ["USER"])
fun `user should not see items through ItemRepository`() {
    assertThrows<AccessDeniedException> { itemRepository.findAll() }
}

this test fails beacuse setUp method, executed before it, fails with AccessDeniedException

@AleksandrSl AleksandrSl changed the title @WithMockUser doesn't work on method annotated as @BeforeEach @WithMockUser doesn't work on method annotated as @BeforeEach Mar 3, 2018
@rwinch
Copy link
Member

rwinch commented Mar 5, 2018

Thanks for the report. This is a duplicate of #2935

@rwinch rwinch closed this as completed Mar 5, 2018
@edwardmp
Copy link

edwardmp commented Jul 19, 2022

@rwinch sorry to resurrect this old issue, but I don't believe this problem has been solved, and also I don't believe it to be a duplicate of the issue you referenced.

The issue you referenced allows to define when the SecurityContext is set: just before test execution OR even before @Before methods.

This issue however is that both the original poster here and I want to have a different security context in the test method and the before method, which doesn't currently seem possible.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants