JPA集成测试的模拟安全环境



我正在尝试测试Spring JPA存储库接口,以确保我的映射正确。我的实体扩展了一个带有注释的基础实体。

@EntityListeners(BaseEntityEventListener.class)
@MappedSuperclass
public abstract class BaseEntity {...

事件侦听器填充了一些审核属性。

public class BaseEntityEventListener {
    @PrePersist
    public void onPreInsert(BaseEntity baseEntity){
        MyUserPrincipal principal = (MyUserPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = principal.getUsername();
        baseEntity.setCreationUser(username);
        Timestamp ts = new Timestamp(System.currentTimeMillis());
        baseEntity.setCreationDate(ts);
    }...

这是可以的,但是当我想测试存储库时,我会为SecurityContexTholder获得空指针。

@RunWith(SpringRunner.class)
@SpringBootTest
public class RepositoryTest {
    @Autowired private MyRepository myRepo;
    @Test
    public void testSaveEntity() throws Exception {
        Entity entity = new Entity(TEST_ID);
        myRepo.save(entity);
    }...

从测试中调用事件侦听器类时,未设置安全上下文。我尝试使用@withmockuser,但这似乎不起作用。我是否可以在服务中包装到安全上下文,然后在我的集成测试中以某种方式嘲笑此调用。如果这是一个选项,我该如何对实体侦听器进行模拟。当我使用@createdby和@createdDate时,安全上下文不是问题,但是我需要手动使用@preinsert出于单独的原因。

您遇到的错误是什么?也许是因为它无法吸引用户。您可以尝试:

val userPrincipal =
                new org.springframework.security.core.userdetails.User(username,
                        "",
                        true,
                        true,
                        true,
                        true,
                        authorities);
        val auth = new TestingAuthenticationToken(userPrincipal, null, authorities);
        auth.setAuthenticated(true);
        SecurityContextHolder.getContext().setAuthentication(auth);

最新更新