我正在使用 Maven + Surefire + TestNG + Guice(最新的稳定版)
我有需要运行 Guice 的“大型”测试。基本上我是这样做的:
@Test(groups = "large")
@Guice(modules = FooLargeTest.Module.class)
public class FooLargeTest {
public static class Module extends AbstractModule {
public void configure() {
bindConstant().annotatedWith(FooPort.class).to(5000);
// ... some other test bindings
}
}
@Inject Provider<Foo> fooProvider;
@Test
public void testFoo() {
Foo foo = fooProvider.get() // here injection of port is done
// it could not be passed to constructor
// ... actual test of foo
}
}
问题是它FooPort
被硬编码为5000
. 这是一个 Maven 属性,所以第一次尝试是使用下一个 Surefire 配置:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
<systemPropertyVariables>
<fooPort>${foo.port}</fooPort>
</systemPropertyVariables>
</configuration>
</plugin>
然后请求它就像System.getProperty("fooPort")
. 不幸的是,文档说,这仅适用于 JUnit 测试。至少在调试测试期间我看不到这个系统变量。我尝试forkMode
了默认的一个和never
,它没有改变任何东西。对于 TestNG 测试,建议这样做:
<properties>
<property>
<name>fooPort</name>
<value>${foo.port}</value>
</property>
</properties>
但是现在我应该使用 Guice 的这个属性,所以应该以某种方式将它提供给 GuiceModule,我尝试了下一个方法:
@Test(groups = "large")
@Guice(moduleFactory = FooLargeTest.ModuleFactory.class)
public class FooLargeTest {
public static class ModuleFactory extends AbstractModule {
private final String fooPort = fooPort;
@Parameters("fooPort")
public ModuleFactory(String fooPort) {
this.fooPort = fooPort;
}
public Module createModule(final ITestContext context, Class<?> testClass) {
return new AbstractModule {
public void configure() {
bindConstant().annotatedWith(FooPort.class).to(fooPort);
// ... some other test bindings
}
}
}
}
@Inject Provider<Foo> fooProvider;
@Test
public void testFoo() {
Foo foo = fooProvider.get() // here injection of port is done
// actual test of foo
}
}
但是这种方式也是失败的,因为创建者modulefactories
没有考虑@Parameters
到,因此无法创建工厂的实例。
看起来我应该尝试从中获取一些数据ITestContext context
,但我不知道数据如何以及是否存在,或者是否有一些更简单的方法可以做我想做的事情。
感谢您的回复。