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

前端 未结 3 1442
梦谈多话
梦谈多话 2021-02-12 14:25

In JUnit tests with Spring MockMVC, there are two methods for authenticating as a Spring Security user: @WithMockUser creates a dummy user with the provided credent

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-12 14:55

    @Inject
    private EntityManager em;
    
    @Inject
    PlatformTransactionManager txManager;
    
    @BeforeTransaction
    public void setup() {
        new TransactionTemplate(txManager).execute(status -> {
    
            User u = new User();
            u.setEMail("test@test.de");
            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 = "test@test.de", userDetailsServiceBeanName = "loadUserByUsername")
    public void test() {
    
    }
    

提交回复
热议问题