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

Comment From: rwinch

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

Comment From: edwardmp

@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.