是否可以将依赖项绑定到TestNG中的拦截器? [英] Is it possible to bind dependencies to interceptor in TestNG?

查看:98
本文介绍了是否可以将依赖项绑定到TestNG中的拦截器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class AbstractTest implements ITestListener {

    @Inject
    protected MobConfiguration mob;

    @Override
    public void onStart(ITestContext context) {
        // TODO Auto-generated method stub
    }
}

当我尝试在侦听器类中注入依赖项时,它总是返回null?有没有可能在侦听器或拦截器实现程序类中处理DI的方法?

When i tried to inject dependencies in listener class, it always returns null? Is there any possible ways to handle DI in listener or interceptor implementer class?

推荐答案

我已成功尝试

I have successfully tried this approach (using a factory, code example at the end of this answer). There is one addition to care for, if you use groups annotations, the thereby discrimination (as in line 126 in code for TestDIFactory.java - there again) seems to work reliable only if you use a testng.xml file.

否则,只有注释参数才是默认情况( l 130,TestDIFactory.java )似乎处于活动状态.只需在 l之后添加if(context.getIncludedGroups().length == 0) throw new NullPointerException("no groups found");,即可轻松进行检查. 122,TestDIFactory.java

Otherwise with annotation parameters only the default case (l. 130, TestDIFactory.java) seems to get active. One can easily check that by adding if(context.getIncludedGroups().length == 0) throw new NullPointerException("no groups found"); after l. 122, TestDIFactory.java

如果您明确需要implements ITestListener,则可以轻松地相应地修改public void onStart(ITestContext context)方法.

If you need the implements ITestListener explicitly it should be easy to modify the public void onStart(ITestContext context) method accordingly.

@Guice(moduleFactory = TestDIFactory.class)
public class YourTestClass {
 @Inject protected MobConfiguration mob;

 @Test(groups = {"unit"})
 public void yourtest() {}
}

在一种情况下,我证明了工厂方法存在问题: 如果工厂提供的模块共享绑定,这意味着绑定在模块A中的一个对象也绑定在另一个模块B中,但是您请求一个组合的模块,该模块在A和B上安装/调用configure,然后由工厂返回.您遇到很大的变化以获得InstantiationException.因此,我的经验法则是:仅在每次测试仅需要一个模块时才工厂.在其他情况下,我使用i. e. @Guice(modules = {TestDIFactory.A.class, TestDIFactory.B.class})假定已授予A和B公共访问权限.

I have proven the factory approach problematic in one case: If the modules provided by the factory share bindings meaning one object bound in module A is also bound in another module B but you request a combined module which installs / calls configure on A and B and then is returned by the factory. You run into a high change to get InstantiationExceptions. So rule of thumb for me: factories only when only one module per test is needed. In other cases I use i. e. @Guice(modules = {TestDIFactory.A.class, TestDIFactory.B.class}) assumed given A and B public access though.

这篇关于是否可以将依赖项绑定到TestNG中的拦截器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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