gpt4 book ai didi

java - JUnit 中的测试数据

转载 作者:行者123 更新时间:2023-12-02 13:36:12 26 4
gpt4 key购买 nike

我是测试新手。所以,我有一个学习任务。

该程序计算二次方程。

例如,如何使用 JUnit 检查 c != 0 且 D > 0?

我想以正确的方式做到这一点。

我尝试从 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);
}
}

}

最佳答案

您的程序在当前形式下不可测试。这是一个替代方案:

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());
}

奖励:在单元测试中比较 double 时,您可能需要使用 this version of assertEquals()由于浮点算术的工作原理和/或二进制数的十进制表示的工作原理,它接受 threshold 参数

关于java - JUnit 中的测试数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42988241/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com