@EntityListeners注入+ jUnit测试 [英] @EntityListeners Injection + jUnit Testing

查看:210
本文介绍了@EntityListeners注入+ jUnit测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在保存到Db中之前和加载之后,我使用@EntityListeners进行操作. 在我的侦听器类中,我调用了Ecryptor(需要从配置文件中获取信息),因此不能静态调用加密器,而需要将其注入到我的侦听器中.对吧?

I use @EntityListeners to make operations before I save in my Db and after I load. Inside my Listener class I make a call to an Ecryptor (which needs to fetch info from configuration file), so the encryptor can't be called statically and need to be injected in my Listener. Right?

好吧,虽然无法立即完成EntityListeners中的注入,但是您可以使用某些方法来做到这一点,例如使用SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);甚至此处显示的方法. https://guylabs.ch/2014/02/22/autowiring-pring-beans-in-hibernate-jpa-entity-listeners/

Well, injections in EntityListeners can't be done straight away, but you have some methods to do that, like using SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); or even the method showed here. https://guylabs.ch/2014/02/22/autowiring-pring-beans-in-hibernate-jpa-entity-listeners/

很酷,问题是:所有解决方案都不支持单元测试!在运行我在模型侦听器中注入的加密程序的测试时,始终为null.

Cool, the problem is: None of the solutions support unit testing! When running tests that encryptor I had injected in my model Listener is always null.

此处 SpringBeanAutowiringSupport不会在jUnit测试中注入bean 有一种创建此上下文并将其传递给实例化对象的解决方案,但是由于我要向其中添加注入",因此它不能解决我的问题.

Here SpringBeanAutowiringSupport does not inject beans in jUnit tests There is a solution to create this context and pass to a instantiated object, but it does not solve my problem since I have the "Injection" to add to it.

在测试中创建上下文并将其以某种方式传递给侦听器的任何方法? 如果没有,我可以通过什么方式为我的Encryptor创建一个静态方法,并且仍然可以访问Environment API来读取我的属性?

Any way to create a context in my tests and somehow pass it to my listeners? If not, any way I can create a static method to my Encryptor and still have access to the Environment API to read my properties?

包监听器:

public class PackageListener{
   @Autowired
   Encryptor encryptor;

   @PrePersist
   public void preSave(final Package pack){
      pack.setBic(encryptor.encrypt(pack.getBic()));
   }
   ...

我的测试

 @Test
 @WithuserElectronics
 public void testIfCanGetPackageById() throws PackageNotFoundException{
     Package pack = packagesServiceFactory.getPackageService().getPackage(4000000002L);
 }

包装服务

  public Package getPackage(Long id) throws PackageNotFoundException{
    Package pack = packageDao.find(id);

    if (pack == null) {
        throw new PackageNotFoundException(id);
    }

    return pack;
}

加密器:

public class Encryptor{
    private String salt;

    public Encryptor(String salt){
        this.salt = salt;
    }

    public String encrypt(String string){
        String key = this.md5(salt);
        String iv = this.md5(this.md5(salt));
        if (string != null) {
            return encryptWithAesCBC(string, key, iv);
        }
        return string;
    }
    ...

推荐答案

您可以创建一个DemoApplicationContextInitializer类,以将appliationContext引用存储在主类的静态属性中.

You can create a DemoApplicationContextInitializer class to store the appliationContext reference in a static property in your main class.

public class DemoApplicationContextInitializer implements
        ApplicationContextInitializer<ConfigurableApplicationContext> {

    @Override
    public void initialize(ConfigurableApplicationContext ac) {
        Application.context = ac;
    }
}


@SpringBootApplication
public class Application {

    public static ApplicationContext context;

    public static void main(String[] args) throws Exception {
        new SpringApplicationBuilder(Application.class)
        .initializers(new DemoApplicationContextInitializer())
        .run(args);
    }
}

然后,您可以在实体侦听器中访问上下文

Then you can access the context in your entity listener

public class PackageListener{
   //@Autowired
   Encryptor encryptor;

   @PrePersist
   public void preSave(final Package pack){
      encryptor = Application.context.getBean(Encryptor.class);
      pack.setBic(encryptor.encrypt(pack.getBic()));
   }
}

要使其在junit测试中起作用,只需像这样在您的测试中添加初始化程序...

And to make this work in your junit test, just add the initializer in your test like this ...

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT, classes = Application.class)
@ContextConfiguration(classes = Application.class, initializers = DemoApplicationContextInitializer.class)
public class MyTest {
...
}

在我的环境中它可以正常工作.希望对您也有帮助.

It works without any issue in my environment. Hope it will be helpful to you too.

这篇关于@EntityListeners注入+ jUnit测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆