Is it possible to bind dependencies to interceptor in TestNG?

随声附和 提交于 2019-12-11 07:16:51

问题


public class AbstractTest implements ITestListener {

    @Inject
    protected MobConfiguration mob;

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

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?


回答1:


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.

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

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() {}
}

EDIT: 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.



来源:https://stackoverflow.com/questions/28825372/is-it-possible-to-bind-dependencies-to-interceptor-in-testng

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!