Java 将泛型与JUnit 4理论一起使用时出错
在尝试将泛型与JUnit4理论混合时,我遇到了一个奇怪的错误。我的代码如下。我基本上想做的是编写一个方法来测试可比较接口的子类型。即使该方法应接受Compariable的任何子类型,但一次只应测试一个子类型(因此,字符串和整数-这两种Compariable子类型-不应一起测试) 作为参考,这是一个明确要求使用理论和泛型的任务,因此我不能使用JUnit的其他部分,也不能省略泛型的使用Java 将泛型与JUnit 4理论一起使用时出错,java,generics,junit,junit4,Java,Generics,Junit,Junit4,在尝试将泛型与JUnit4理论混合时,我遇到了一个奇怪的错误。我的代码如下。我基本上想做的是编写一个方法来测试可比较接口的子类型。即使该方法应接受Compariable的任何子类型,但一次只应测试一个子类型(因此,字符串和整数-这两种Compariable子类型-不应一起测试) 作为参考,这是一个明确要求使用理论和泛型的任务,因此我不能使用JUnit的其他部分,也不能省略泛型的使用 @RunWith(Theories.class) public class ComparableTheory{
@RunWith(Theories.class)
public class ComparableTheory{
@DataPoints public static String[] stringPoints() {
return new String[] {
"abc",
"acc"
};
}
@DataPoints public static String[] stringPoints2() {
return new String[] {
"xyz",
"mno"
};
}
@DataPoints public static Integer[] integerPoints() {
return new Integer[] {
1, 2, 3
};
}
@Theory
public <T extends Comparable> void comparableTransitiveTheory(T a, T b, T c) {
assumeTrue (Math.signum(a.compareTo(b)) == Math.signum(b.compareTo(c)));
assertTrue (Math.signum(a.compareTo(c)) == Math.signum(a.compareTo(b)));
}
}
文件
hamcrest-2.1.jar
和junit-4.13-beta-2.jar
在我的工作目录中(因此,在我的类路径中)。如何在eclipse中运行此类?@RayTayek感谢您的回复-我不在eclipse中运行它;我正在从命令行运行。我在类路径中包括JUnit和Hamcrest JAR。如何从命令行运行?您可以在目录中共享吗?您可能需要使用:T extends comparable我遇到了与您相同的错误。您如何在eclipse中运行此类?@RayTayek感谢您的回答-我不在eclipse中运行它;我正在从命令行运行。我在类路径中包括JUnit和Hamcrest JAR。如何从命令行运行?你能分享一下吗?你可能需要使用:T extends comparable我得到了和你一样的错误。
JUnit version 4.13-beta-2
.E
Time: 0.002
There was 1 failure:
1) initializationError(ComparableTheory)
org.junit.runners.model.InvalidTestClassError: Invalid test class 'ComparableTheory':
1. Method comparableTransitiveTheory() contains unresolved type variable T
2. Method comparableTransitiveTheory() contains unresolved type variable T
3. Method comparableTransitiveTheory() contains unresolved type variable T
at org.junit.runners.ParentRunner.validate(ParentRunner.java:511)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:91)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:74)
at org.junit.experimental.theories.Theories.<init>(Theories.java:73)
FAILURES!!!
Tests run: 1, Failures: 1
javac -cp .:"*" ComparableTheory.java
java -cp .:"*" org.junit.runner.JUnitCore ComparableTheory