TestNG-在Guice模块中访问ITestContext

时间:2019-04-14 15:42:53

标签: testng guice

我试图按照这个问题去做。

Is there a way to inject ITestContext from TestNg to guice module?

请考虑以下问题:

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中的错误吗?

我希望自己能看到

Parent module called
configure is called :: Test1
configure is called :: Test2
configure is called :: Test3

如何在GuiceModule中访问ITestContext?

1 个答案:

答案 0 :(得分:0)

TestParentModule明确将ITestConext绑定到特定实例。而且ParentModule仅被调用一次。因此,基本上将注入相同的实例。不确定是否是错误。可以按照他们的设计!

    @Override
    protected void configure() {
        System.out.println("Parent module called");
        bind(ITestContext.class).toInstance(iTestContext);
    }

正如Jens在评论中指出的那样,使用IModuleFactory可以解决您的问题。

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);
    }

}