java - 如何将参数注入(inject)TestNG类的构造函数?

标签 java testing parameters constructor

我已经实现了一个具有策略模式的程序。所以我有一个在某些地方使用的接口(interface),并且具体实现可能会被替换。

现在我想测试这个程序。我想以类似的方式来做。编写一次测试,针对接口(interface)进行测试。具体的接口(interface)实现应该在测试开始时注入(inject),这样我就可以轻松替换它。

我的测试类看起来与这个类似:

public class MyTestClass {

    private StrategeyInterface strategy;

    public MyTestClass(StrategeyInterface strategy) {
        this.strategy = strategy;
    }
    ....test methods using the strategy.
}

参数化构造函数必须在测试开始时注入(inject)具体的策略实现。

现在我没有让 TestNG 运行它并注入(inject)具体的实现实例。我尝试了多种继承、@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>

如何编写和运行测试,并将具体实现注入(inject)到测试类中?

提前致谢。

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

最佳答案

您有多种选择。如果您使用 Guice,here is a very straightforward way to inject your implementation .

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

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

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

关于java - 如何将参数注入(inject)TestNG类的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6902693/

相关文章:

testing - Cypress UI 可以看到我的规范文件,但无法正常工作

php - 在 php mysql 查询中添加更多搜索变量时遇到问题

java - 如何读取和写入多个子文件夹?

java - javax.annotation.Nonnull 是否会影响运行时行为?

java - 使用 Selenium Webdriver 滚动时获取 AJAX 内容加载

spring - 将模型属性添加到 spring MockMvc 调用

java - Hibernate @OrderBy 注释和 MySQLSyntaxErrorException

Randoop 的 Java 类路径问题

eclipse - Birt Report 同一字段的多个参数

python - python中动态添加参数