我有一个实体,并且希望实现审计和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类获得了getBean()方法中上下文中的空指针异常。
@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);
}
}发布于 2019-02-28 20:53:47
这就是我在考试课上解决问题的方法。
@Autowired context;
在测试方法中调用
BeanUtil beanUtil = new BeanUtil();
beanUtil.setApplicationContext(context);而且起作用了。
发布于 2019-02-27 19:12:00
问题是,您不是在使用spring的AOP,而是使用静态上下文:
private static ApplicationContext context;它是空的,因为不创建@Bean会导致未代理的对象。解决方案是@Autowire它。
https://stackoverflow.com/questions/54912438
复制相似问题