Skip to content

@WithUserDetails setupBefore does not work with JUnit 5 #6591

@sirgrigio

Description

@sirgrigio

Summary

When using JUnit 5 it seems that setting the setupBefore parameter of @WithUserDetails to TestExecutionEvent.TEST_EXECUTION does not work as intended. In fact it appears that the security context is created before the execution of a @BeforeEach method.

Actual Behavior

I wrote the following test class to showcase the issue

@ExtendWith(SpringExtension.class)
@ContextConfiguration
class WithUserDetailsTest {

  private static String USERNAME;

  @BeforeEach
  void setUp() {
    USERNAME = "dummy";
  }

  @Test
  @WithUserDetails(
      userDetailsServiceBeanName = "testUserDetailsService",
      setupBefore = TestExecutionEvent.TEST_EXECUTION
  )
  void test() {
    TestUserDetails principal = (TestUserDetails) SecurityContextHolder.getContext()
        .getAuthentication().getPrincipal();
    Assertions.assertNotNull(principal.getUsername());
  }

  @Configuration
  static class TestUserDetailsConfiguration {

    @Bean("testUserDetailsService")
    UserDetailsService testUserDetailsService() {
      return s -> new TestUserDetails(USERNAME);
    }
  }

  static class TestUserDetails implements UserDetails {

    private static final long serialVersionUID = -6779736987183888865L;

    private String username;

    TestUserDetails(String username) {
      this.username = username;
    }

    @Override
    public String getUsername() {
      return username;
    }

    ...
  }
}

What happens here is that the test keeps failing because when the UserDetails is actually loaded the USERNAME variable is still null.

Expected Behavior

I would expect the @BeforeEach method to be executed before the SecurityContext initialization therefore allowing the creation of a UserDetails with a non null username.

Configuration

Version

I am using Spring Boot Dependency 2.1.3.RELEASE (=> Spring Security Test 5.1.4.RELEASE).

Sample

Metadata

Metadata

Assignees

Labels

in: testAn issue in spring-security-teststatus: duplicateA duplicate of another issue

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions