auditingentityListener Junit找不到上下文



我有一个实体,想实现审计和audithistory,两者都有效,但在单元测试应用程序上下文时。

实体

@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@EntityListeners(UserListener.class)
public class User extends BaseModel<String> {
    @Column
    private String username;
    @Column
    private String password;
    @Transient
    private String passwordConfirm;
    @ManyToMany
    private Set<Role> roles;
}

userListener

public class UserListener {
    @PrePersist
    public void prePersist(User target) {
        perform(target, INSERTED);
    }
    @PreUpdate
    public void preUpdate(User target) {
        perform(target, UPDATED);
    }
    @PreRemove
    public void preRemove(User target) {
        perform(target, DELETED);
    }
    @Transactional(MANDATORY)
    void perform(User target, Action action) {
        EntityManager entityManager = BeanUtil.getBean(EntityManager.class);
        if(target.isActive()){
            entityManager.persist(new UserAuditHistory(target, action));
        }else{
            entityManager.persist(new UserAuditHistory(target, DELETED));
        }
    }
}

Useraudithistory

@Entity
@EntityListeners(AuditingEntityListener.class)
public class UserAuditHistory {
    @Id
    @GeneratedValue
    private Long id;
    @ManyToOne
    @JoinColumn(name = "user_id", foreignKey = @ForeignKey(name = "FK_user_history"))
    private User user;
    @CreatedBy
    private String modifiedBy;
    @CreatedDate
    @Temporal(TIMESTAMP)
    private Date modifiedDate;
    @Enumerated(STRING)
    private Action action;
    public UserAuditHistory() {
    }
    public UserAuditHistory(User user, Action action) {
        this.user = user;
        this.action = action;
    }
}

beanutil用于获取和设置上下文

@Service
public class BeanUtil implements ApplicationContextAware {
    private static ApplicationContext context;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
    public static <T> T getBean(Class<T> beanClass) {
        return context.getBean(beanClass);
    }
}

现在,我从上下文中的上下文中从上面的beanutil类中获得了null指针异常()方法。

@RunWith(SpringRunner.class)
@DataJpaTest
public class UserRepositoryTest{
    @Autowired
    private TestEntityManager entityManager;
    @Autowired
    private UserRepository repository;
    @Test
    public void whenFindAll_theReturnListSize(){
        entityManager.persist(new User("jk", "password", "password2", null));
        assertEquals(repository.findAll().size(), 1);
    }
}

这就是我解决问题的方式,在测试类中

@autowiredApplicationContext上下文;

在测试方法中称为

BeanUtil beanUtil = new BeanUtil();
beanUtil.setApplicationContext(context);

它起作用。

问题是,您不使用Spring的AOP,而是静态上下文:

private static ApplicationContext context;

这是空的,因为不创建@Bean会导致无抵抗的对象。解决方案将是@Autowire IT。

最新更新