【问题标题】:how to inject datasource into testng method execution listener如何将数据源注入testng方法执行监听器
【发布时间】:2016-02-16 21:36:53
【问题描述】:

我有一个方法级别的侦听器,看起来像这样

   public class DefaultListener implements IInvokedMethodListener2 {
       @Autowired
       JdbcTemplate jdbcTemplate;        

        public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
        }

        public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
        }

        public void beforeInvocation(IInvokedMethod method, ITestResult testResult,
                ITestContext context) {
           updateDatabaseWithTestStartTime();           
        }
        private void updateDatabaseWithTestStartTime() {
           jdbcTemplate.update("....");
        }

        // other methods.
}

如何在上面的示例中自动装配 jdbcTemplate?我查看了 spring-test 和与 test-ng 的集成,但是像 these 这样的例子正在讨论在测试级别控制自动装配 - 我的需求是特定于侦听器的。

【问题讨论】:

  • 监听器不是spring容器管理的,为什么需要它来自动装配?
  • Testng 与 Guice 开箱即用,但即使使用这种集成,也无法注入到侦听器中。你需要找到另一种方法来找到你想要的对象引用。
  • 如您所见,我想访问数据库并向其中写入一些数据。为了写入数据库,我必须使用数据访问层 (DAO),它是一个已经有 @Autowired jdbc 模板的共享项目。所以,我必须初始化 spring 才能自动连接数据访问层。
  • 好的,这就是我到目前为止所做的。在 ISuiteListener 的 onStart(ISuite) 方法中,我使用此代码启动了一个应用程序上下文 - new ClassPathXmlApplicationContext("classpath*:spring-context.xml");"我现在如何使这个上下文可用于我的 IInvokedMethodListener?

标签: java spring testng spring-test


【解决方案1】:

IInvokedMethodListener2 是一个 TestNG 侦听器,因此与 Spring TestContext Framework 无关。

如果您想在可重用的侦听器中与 Spring ApplicationContext 中的 bean 进行交互,则需要实现 Spring TestExecutionListener

查看SqlScriptsTestExecutionListener 以获取有关如何实现此类侦听器的灵感。

有关详细信息,请阅读 Spring 参考手册的 Testing 章节中有关“TestExecutionListener”的所有讨论,特别注意 TestExecutionListener configuration 部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 2012-01-30
    • 2015-08-19
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多