我正在尝试为计算矩阵对角线之和差的小函数编写测试用例(使用 Java、Maven、Junit、Eclipse)。
待测函数
public static int diagonalDifference(Integer matrix[][], int n) {
int diagonalSum1 = 0;
int diagonalSum2 = 0;
int diagonalDifference = 0;
for (int i = 0; i < n; i++) {
diagonalSum1 = diagonalSum1 + matrix[i][i];
diagonalSum2 = diagonalSum2 + matrix[i][Math.abs(i - 2)];
}
diagonalDifference = Math.abs(diagonalSum1 - diagonalSum2);
return diagonalDifference;
}
}
来自这个答案https://stackoverflow.com/a/19349565/7115684我没有成功尝试类似的东西,
public class testSolutions {
Solution solution = new Solution();
Integer a[][] = { { 11, 2, 4 }, { 4, 5, 6 }, { 10, 8, -12 } };
Integer b[][] = { { 12, 22, 8 }, { 2, 16, 8 }, { 10, 5, -1 } };
@DataProvider
public Object[][] provideMatrixAndExpectedSum() {
return new Object[][] { { a, new Integer(15) } };
}
@Test
@UseDataProvider("provideMatrixAndExpectedSum")
public void test(Integer a[][], int n) {
int diagonalDifference = Solution.diagonalDifference(a, n);
assertEquals(diagonalDifference, 15);
}
}
当我运行它时,我得到一个错误“方法测试应该没有参数。”
我的问题是:
- 如何为这种情况编写测试用例?
- 如何准备测试数据?
- 我们能否在资源文件夹中创建一个类似属性文件的文件,以便它也可以提供给其他功能。
最佳答案
好像要测试的函数接受一个二维数组,返回一个整数,你需要测试返回的值是否正确。 我有一个使用 JUint 的类似代码和测试单元。不要理会我的代码做了什么,只关注传递了什么输入和要验证的输出。
public class countUniqueNums {
public int countUnique (int[] nums) {
int unique=0;
int [] intVal = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
for (int i = 0; i<nums.length; i++) {
intVal[nums[i]+9]++;
if (intVal[nums[i]+9]==1)
unique++;
else
if (intVal[nums[i]+9]==2)
unique--;
}
return unique;
}
}
测试单元如下:
import static junitparams.JUnitParamsRunner.$;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
@RunWith(JUnitParamsRunner.class)
public class countUniqueNumsParamTest {
@SuppressWarnings({ "unused", "deprecation" })
private static final Object[] countUniqueNumbers () {
return $(
// Parameters are (1,2), 1=expected result count, 2= input array
$(1,new int[]{0}), //Test Case 1
$(0,new int[]{}), //Test Case 2
$(0,new int[]{0,0}), //Test Case 3
$(0,new int[]{0,0,0}), //Test Case 4
$(1,new int[]{0,1,1,1}), //Test Case 5
$(1,new int[]{1,1,1,0}), //Test Case 6
$(2,new int[]{1,0,2,1}), //Test Case 7
$(4,new int[]{0,1,2,3}) //Test Case 8
);
}
@Test
@Parameters(method="countUniqueNumbers")
public void test(int unique, int[] nums) {
countUniqueNums cun = new countUniqueNums();
assertEquals(unique, cun.countUnique(nums));
}
}
确保您在 eclipse 中为 JUnit 导入正确的库。定制您的测试用例类以匹配我的,您应该可以开始了。 希望这会有所帮助。
关于java - 如何准备和提供测试数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43397842/