Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring boot TestExecutionListeners中的Spring引导autowire依赖项_Spring Boot - Fatal编程技术网

Spring boot TestExecutionListeners中的Spring引导autowire依赖项

Spring boot TestExecutionListeners中的Spring引导autowire依赖项,spring-boot,Spring Boot,情况:有一个服务器将接受我交给它的测试结果,但只提供适当的授权和客户端配置。因此,我编写了一个客户机类作为bean,从application.properties加载正确的凭据(在同一个庄园中,您可以使用凭据和spring的属性连接到数据库)。我现在想编写一个testng侦听器,它使用这个客户机来完成这项工作。通过研究,我发现Spring应该做的事情是扩展AbstractTestExecutionListener 因此,如果我将我的客户机作为类成员自动连接,就像下面的@Autowired pri

情况:有一个服务器将接受我交给它的测试结果,但只提供适当的授权和客户端配置。因此,我编写了一个客户机类作为bean,从application.properties加载正确的凭据(在同一个庄园中,您可以使用凭据和spring的属性连接到数据库)。我现在想编写一个testng侦听器,它使用这个客户机来完成这项工作。通过研究,我发现Spring应该做的事情是扩展
AbstractTestExecutionListener

因此,如果我将我的客户机作为类成员自动连接,就像下面的
@Autowired private-MyClient我可以看到bean的创建是正确的,但是如果我尝试在我的侦听器中这样使用它:

@TestExecutionListeners(mergeMode = MergeMode.MERGE_WITH_DEFAULTS, listeners = {MyListener.class})
public abstract class MyTestParent extends AbstractTestNGSpringContextTests { //...
我可以看到bean不是自动连接的,这使我相信这些侦听器在spring上下文之外被实例化为bean本身


如何编写一个监听器(特定于spring或testng),它可以从spring上下文将依赖项连接到监听器中?如果我想将结果推送到其他任意的测试结果存储库(如数据库),该怎么办?

Spring不会自动连接TestListeners中的依赖项。 但您可以访问beanfactory并使用它自动连接侦听器本身:

public class CustomTestExecutionListener extends AbstractTestExecutionListener {

    @Autowired
    TestSupport support;

@Override
public void beforeTestClass(TestContext testContext) throws Exception {
    //get the beanfactory and use it to inject into this
    testContext.getApplicationContext()
            .getAutowireCapableBeanFactory()
            .autowireBean(this);

    //now use the autowired field 
    support.beforeClass();
}
。。。
}Spring不会自动连接TestListeners中的依赖项。 但您可以访问beanfactory并使用它自动连接侦听器本身:

public class CustomTestExecutionListener extends AbstractTestExecutionListener {

    @Autowired
    TestSupport support;

@Override
public void beforeTestClass(TestContext testContext) throws Exception {
    //get the beanfactory and use it to inject into this
    testContext.getApplicationContext()
            .getAutowireCapableBeanFactory()
            .autowireBean(this);

    //now use the autowired field 
    support.beforeClass();
}
。。。
}

这并不是我最终要做的,但它确实直接回答了我的问题。谢谢这不是我最后要做的,但它确实直接回答了我的问题。非常感谢。