java - JUnit 中的测试数据

标签 java unit-testing junit

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

该程序计算二次方程。

例如,如何使用 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/

相关文章:

java - 如何使用 SoundPool 播放随机声音?

testing - 我如何测试 Zkoss 中注解 @Listen 的正确性?

java - 使用java问题将数据插入sql

java - 测试从输入流中读取的缓冲读取器

java - 包 com.felees.hbnpojogen.persistence 不存在

unit-testing - MassTransit 服务总线配置和单元测试

c++ - eclipse 和 boost unit_test_framework 使用 c++ 进行语法检查失败

android - 如何在 Android 单元测试期间使用 emma 进行代码覆盖

unit-testing - 单元测试 - 测试用例与多种方法

java - org.dbunit.database - junit.framework.ComparisonFailure - 表顺序每次运行都不同