gpt4 book ai didi

java - AuditingEntityListener junit 找不到上下文

转载 作者:行者123 更新时间:2023-12-02 01:38:01 25 4
gpt4 key购买 nike

我有一个实体,想要实现 Audit 和 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;
}

用户监听器

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));
}

}
}

用户审核历史记录

@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);
}
}

现在是 Junit,我在 getBean() 方法中从上述 BeanUtil 类的上下文中获得空指针异常。

@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);

并且成功了。

关于java - AuditingEntityListener junit 找不到上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54912438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com