Spring Security, JUnit: @WithUserDetails for user created in @Before

Use setupBefore = TEST_EXECUTION

This will effectively cause @WithUserDetails to execute after @Before and @BeforeEach

@BeforeEach
public void createUser() {
   ...
}

@Test
@WithUserDetails(value = "username", setupBefore = TestExecutionEvent.TEST_EXECUTION)
public void expectToWork() {
   ...
}

Unfortunately, you can't do easily @WithUserDetails with @Before, because Spring @WithUserDetails annotation will invoke Spring security context test listener before running setUp method with @Before.

Here is https://stackoverflow.com/a/38282258/1814524 a little trick and answer to your question.


You can use @PostConstruct instead of @Before. That did the trick for me. Can anybody confirm that?


@Inject
private EntityManager em;

@Inject
PlatformTransactionManager txManager;

@BeforeTransaction
public void setup() {
    new TransactionTemplate(txManager).execute(status -> {

        User u = new User();
        u.setEMail("[email protected]");
        em.save(u);

        return null;
    });
}

@AfterTransaction
public void cleanup() {
    new TransactionTemplate(txManager).execute(status -> {
        // Check if the entity is managed by EntityManager.
        // If not, make it managed with merge() and remove it.
        em.remove(em.contains(u) ? user1 : em.merge(u));
        return null;
    });
}


@Test
@Transactional
@WithUserDetails(value = "[email protected]", userDetailsServiceBeanName = "loadUserByUsername")
public void test() {

}