Java 如何将参数注入TestNG类的构造函数中?

Java 如何将参数注入TestNG类的构造函数中?,java,testing,parameters,constructor,Java,Testing,Parameters,Constructor,我已经用策略模式实现了一个程序。因此,我有一个在某些地方使用的接口,具体的实现可能会被替换 现在我想测试这个程序。我想用类似的方法来做。编写一次测试,对接口进行测试。具体的接口实现应该在测试开始时注入,以便我可以轻松地替换它 我的testclass与此类似: public class MyTestClass { private StrategeyInterface strategy; public MyTestClass(StrategeyInterface strategy

我已经用策略模式实现了一个程序。因此,我有一个在某些地方使用的接口,具体的实现可能会被替换

现在我想测试这个程序。我想用类似的方法来做。编写一次测试,对接口进行测试。具体的接口实现应该在测试开始时注入,以便我可以轻松地替换它

我的testclass与此类似:

public class MyTestClass {

    private StrategeyInterface strategy;

    public MyTestClass(StrategeyInterface strategy) {
        this.strategy = strategy;
    }
    ....test methods using the strategy.
}
参数化构造函数必须用于在测试开始时注入具体的策略实现

现在我没有让TestNG运行它并注入具体的实现实例。我用继承、
@DataProvider
@Factory
和相应的方法尝试了几种方法,但没有成功

以下是testNG报告的内容:

Can't invoke public void MyClass.myTestMethod(): either make it static or add a no-args constructor to your class
我使用maven surefire插件来运行测试。以下是pom.xml的相关部分:

    <build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <suiteXmlFiles>
                    <suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
                </suiteXmlFiles>
            </configuration>
        </plugin>
    </plugins>
</build>

org.apache.maven.plugins
maven surefire插件
src/test/resources/testng.xml
如何编写和运行测试,并在测试类中注入具体的实现?

提前谢谢


另外,我可以提供更多我尝试过的代码。我还没有在这里发布,因为我尝试了太多的变体,所以我现在有点困惑,所有的变体都失败了

您有几种选择。如果您使用的是Guice

如果没有,您可以混合使用工厂和数据提供程序:

@Factory(dataProvider = "dp")
public FactoryDataProviderSampleTest(StrategyInterface si) {
}

@DataProvider
static public Object[][] dp() {
  return new Object[][] {
    new Object[] { new Strategy1Impl() },
    new Object[] { new Strategy2Impl() },
  };
}