中值函数的 JUnit 参数化测试
我正在尝试为一个函数编写 JUnit 测试,该函数查找给定 double
元素数组的中位数。
但是,我在传递参数方面遇到了困难。我的代码如下所示:
@RunWith(Parameterized.class)
public class MedianParameterizedTest extends TestCase {
private Double[] numbers;
private Double expectedMedian;
public MedianParameterizedTest(Double[] numbers, double expectedMedian){
this.numbers = numbers;
this.expectedMedian = expectedMedian;
}
@Parameterized.Parameters
public static Collection medianArrays() {
return Arrays.asList(new Object[][] {
{ {-5.0,-4.0,3.0}, -4.0}
});
}
@Test
public void test1() {
//doing test
}
}
但这给了我一个非法的初始化器 for java.lang.Object 错误的中值数组集合,我无法找出原因。
I am trying to write a JUnit test for a function that finds the median for a given array of double
elements.
However, I am struggling with passing the parameters. My code looks like this:
@RunWith(Parameterized.class)
public class MedianParameterizedTest extends TestCase {
private Double[] numbers;
private Double expectedMedian;
public MedianParameterizedTest(Double[] numbers, double expectedMedian){
this.numbers = numbers;
this.expectedMedian = expectedMedian;
}
@Parameterized.Parameters
public static Collection medianArrays() {
return Arrays.asList(new Object[][] {
{ {-5.0,-4.0,3.0}, -4.0}
});
}
@Test
public void test1() {
//doing test
}
}
But this gives me an illegal initializer for java.lang.Object error for the medianArrays collection and I can't find out why.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要使用 new Double[] 为每个测试创建第一个(数组)参数。
您的代码中有三层嵌套数组:
在
new Object[][]
之后,Java 知道需要两层嵌套数组。在new Object[][] {
之后,它仍然知道还有一层数组需要等待,但是在new Object[][] { {
> 之后,它就不再需要了期待更多级别的嵌套数组。如果此时要创建数组,则必须指定类型。请尝试以下方法:
You need to create the first (array) argument for each test using
new Double[]
.You have three levels of nested arrays in your code:
After
new Object[][]
, Java knows that two levels of nested arrays are to be expected. Afternew Object[][] {
, it still knows that there is one more level of array to expect, but afternew Object[][] { {
, it's not expecting any more further levels of nested array. If you want to create an array at this point you must specify the type.Try the following instead: