问题描述
我正试图按照这个问题去做.
I was trying to do as per this question.
是有没有办法将ITestContext从TestNg注入guice模块?
请考虑以下问题:
public class TestParentModule extends AbstractModule {
private ITestContext iTestContext;
public TestParentModule(ITestContext iTestContext){
this.iTestContext = iTestContext;
}
@Override
protected void configure() {
System.out.println("Parent module called");
bind(ITestContext.class).toInstance(iTestContext);
}
}
public class TestModule extends AbstractModule {
@Inject
private ITestContext iTestContext;
@Override
protected void configure() {
System.out.println("configure is called :: " + iTestContext.getName());
}
}
套房
<suite name="My suite" parent-module="com.mypackage.guice.TestParentModule">
<test name="Test1" >
<classes>
<class name="com.mypackage.SampleTest"/>
</classes>
</test>
<test name="Test2" >
<classes>
<class name="com.mypackage.SampleTest"/>
</classes>
</test>
<test name="Test3" >
<classes>
<class name="com.mypackage.SampleTest"/>
</classes>
</test>
</suite>
测试类带有
@Guice(modules = TestModule.class)
输出::
Parent module called
configure is called :: Test1
configure is called :: Test1
configure is called :: Test1
有趣的是,它每次都注入相同的ITestContext实例吗?这不是TestNG中的错误吗?
Interestingly it injects same ITestContext instance every time? Is it not a bug in TestNG?
我希望自己能看到
Parent module called
configure is called :: Test1
configure is called :: Test2
configure is called :: Test3
如何在GuiceModule中访问ITestContext?
How can I access ITestContext in the GuiceModule?
推荐答案
TestParentModule明确将ITestConext绑定到特定实例.而且ParentModule仅被调用一次.因此,基本上将注入相同的实例.不知道这是否是一个错误.可以按照他们的设计!
The TestParentModule clearly binds the ITestConext to specific instance. Also ParentModule is invoked only once. So it is basically going to inject the same instance. Not sure if it is a bug. Could be as per their design!
@Override
protected void configure() {
System.out.println("Parent module called");
bind(ITestContext.class).toInstance(iTestContext);
}
正如Jens在评论中指出的那样,使用IModuleFactory
可以解决您的问题.
As Jens has pointed out in the comment, using IModuleFactory
would solve your problem.
public class ModuleFactory implements IModuleFactory {
@Override
public Module createModule(ITestContext iTestContext, Class<?> aClass) {
return new TestModule(iTestContext);
}
}
public class TestModule extends AbstractModule {
private ITestContext iTestContext;
public TestModule(ITestContext iTestContext){
this.iTestContext = iTestContext;
}
@Override
protected void configure() {
//do something with iTestConext
bind(ITestContext.class).toInstance(iTestContext);
}
}
这篇关于TestNG-在Guice模块中访问ITestContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!