【发布时间】:2011-10-17 16:15:42
【问题描述】:
我已经用策略模式实现了一个程序。所以我有一个在某些地方使用的接口,具体实现可能会被替换。
现在我想测试这个程序。我想以类似的方式做到这一点。编写一次测试,针对接口进行测试。具体的接口实现应该在测试一开始就注入,这样我就可以轻松替换了。
我的测试类看起来和这个类似:
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>
如何编写和运行测试,将具体实现注入测试类?
提前致谢。
附:我可以提供更多我尝试过的代码。我还没有在这里发布它,因为我尝试了很多变体,所以我现在有点困惑并且所有变体都失败了。
【问题讨论】:
标签: java testing parameters constructor