问题
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 InstantiationException
s. 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