我是测试的新手。所以,我有一个学习任务。
该程序计算二次方程。
我如何检查,例如,c!= 0和D> 0使用JUnit?
我想以正确的方式做到这一点。
我试图从JUnit调用input(),但测试变得无穷无尽。
public class Main {
public static Scanner input;
public static double a, b, c;
public static double d;
public static double x1, x2;
public static void main(String args []) {
input();
}
public static void input() {
System.out.println("ax^2 + bx + c = 0");
input = new Scanner(System.in);
try {
System.out.print("a -> ");
a = input.nextFloat();
System.out.print("b -> ");
b = input.nextFloat();
System.out.print("c -> ");
c = input.nextFloat();
} catch (InputMismatchException e) {
System.out.println("Input number!\n");
input();
}
if(a == 0 || b == 0 || c == 0) {
System.out.println("Not right\n");
input();
return;
}
calculate();
}
public static void calculate() {
d = (b * b) - (4 * a * c);
System.out.println("D = " + d);
if(d < 0) {
System.out.print("No answer");
} else if(d == 0) {
x1 = (-b) / (2 * a);
System.out.println ("x = " + x1);
} else {
x1 = (-b + Math.sqrt(d)) / (2 * a);
x2 = (-b - Math.sqrt(d)) / (2 * a);
System.out.println("x1 = " + x1);
System.out.println("x2 = " + x2);
}
}
}
答案 0 :(得分:1)
您的程序目前的形式无法测试。这是另一种选择:
public class Parabola {
// These are required in the constructor. Omitted for brevity
private final double a;
private final double b;
private final double c;
// Public API. Test this
public double x1() { /*...*/ }
public double x2() { /*...*/ }
}
现在编写测试很简单:
@Test public void test1() {
Parabola target = new Parabola(1, 2, 3);
assertEquals(target.x1(), 44.23);
assertEquals(target.x2(), 17.23);
}
@Test public void test2() {
Parabola target = new Parabola(1, 0, 0);
assertEquals(target.x1(), -1);
assertEquals(target.x2(), 13.43);
}
最后这就是main()
的样子:
public void main(String... args) throws Exception {
Scanner console = ...;
System.out.println("Type a:");
Double a = Double.parseDouble(console.nextLine());
// Same for b and c
Parabola p = new Parabola(a, b, c);
System.out.println("X axis intersected in " + p.x1() + " and " + p.x2());
}
Bonus:在单元测试中比较double
时,您可能希望使用接受threshold
参数的this version of assertEquals()
,因为浮点运算的工作方式和/或二进制数的十进制表示