我正在尝试为下面的每个功能创建j单元测试,但是我不知道如何开始。就我而言,使用函数本身并在单元案例中对其进行测试真的很困难。我只知道如何测试特定的值/列表。我需要了解如何测试功能本身的帮助。
public class FindValues {
/**
* @param args
*/
public static void main(String[] args) {
int[] x = new int[] {2,5,6};
int y = 2;
findLast(x, y);
int[] x1 = new int[] {1,2,0};
lastZero(x1,y);
int[] x2 = new int[] {-3, 3, 5, 0};
countPositive(x2,y);
int[] x3 = new int[] {-6, 2, -1, 1};
oddOrPos(x3);
}
// findlast(int [] x, int y) takes an array of integers and should return the index of
// the last element in the array that is equal to y.
public static int findLast(int [] x, int y) {
x = new int[]{2,5,6};
y = 2;
for (int i=x.length-1; i >= 0; i--) {
if (x[i] == y) {
// System.out.println(i);
return i;
}
}
return -1;
} //end FindLast
// lastZero(int [] x) takes an array of integers and should return the index of the last//0 in x.
public static int lastZero (int[] x, int y) {
x = new int[]{1,2,0};
for (int i = 0; i < x.length; i++)
{
if (x[i] == 0)
{
System.out.println(i);
}
}
return -1;
}
public static int countPositive (int[] x, int y) {
//Returns the number of positive elements in Xint count = 0;
x = new int[]{-3, 3, 5, 0};
int count = 0;
for (int i=0; i < x.length; i++) {
if (x[i] > 0) {
count++;
}
}
System.out.println(count);
return count;
}
public static int oddOrPos(int[] x) {
//Return numbers in x that are either odd or positive or both int count = 0;
int count = 0;
x = new int[]{-6, 2, -1, 1};
for (int i = 0; i < x.length; i++) {
if (x[i]% 2 == -1 || x[i]% 2 == 1 || x[i] > 0) {
count++;
}
}
System.out.println(count);
return count;
}
}
答案 0 :(得分:0)
您应该先阅读JUnit User Guide,然后进行research来查找示例和教程。
基本上,您要做的是创建一个JUnit类,该类将测试您的FindValues
类。通常,您将以正在测试的类命名该类。例如,FindValuesTest
。
我将开始一个非常基本的测试,其中包含一个基本的断言,但是我认为值得阅读文档并使用JUnit一段时间。一旦有了made an attempt创建JUnit的知识并陷入困境,那么您应该回到这里,通过添加尝试和问题的所有相关细节来编辑问题。 (请参阅How to Ask a Good Question)
如所保证的,这是一个非常基本的示例,可以帮助您入门:
import static org.junit.Assert.*;
import org.junit.Test;
public class FindValuesTest {
@Test
public void test() {
int actualResult = FindValues.findLast(new int[]{1,2,3,4,2,5,8,2,9}, 2);
assertEquals(7, actualResult);
}
}
请注意,我删除了findLast
中的硬编码参数值:
public static int findLast(int[] x, int y) {
for (int i = x.length - 1; i >= 0; i--) {
if (x[i] == y) {
// System.out.println(i);
return i;
}
}
return -1;
}
查看测试如何向您的方法提供输入,并断言输出符合期望-这就是JUnit要做的事情。您执行一些要测试的代码,并根据测试提供的输入来验证该代码的行为。