关于JUnit的疑问和建议

时间:2014-04-19 15:30:46

标签: java junit

我有一个java类,它包含一些关于整数数组中二进制搜索的方法。 现在我应该创建一个新类来验证这些方法的正确性,使用不同的数组和不同的元素来测试这些方法。 就目前而言,我已经在一个"标准中完成了这一类新的测试。方式,但我知道我可以使用JUnit。 我在互联网上搜索了一些简单的指南,但我不太了解。

例如,如果我的班级"主要" BinarySearch.java 以这种方式制作:

public class BinarySearch {

    private BinarySearch() { }

    public static int find(int x, int[] a) {
        int i = 0;
        int inf = 0;
        int sup = a.length - 1;
        if(sup == -1 || x < a[0] || x > a[sup])
            return -1;
        while(inf <= sup) {
            i = (inf + sup) >>> 1; 
            if(x < a[i])
                sup = i - 1;
            else if(x > a[i])
                inf = i + 1;
            else
                return i;
        }
        return -1;
    }

    public static boolean isPresent(int x, int[] a) {
        int i = 0;
        int inf = 0;
        int sup = a.length - 1;
        if(sup == -1 || x < a[0] || x > a[sup])
            return false;       
        while(inf <= sup) {
            i = (inf + sup) >>> 1; 
            if(x < a[i])
                sup = i - 1;
            else if (x > a[i])
                inf = i + 1;
            else
                return true;
        }
        return false;
    }

    public static void sort(int[] a) {
        int b, c;
        int temp;
        int s = a.length - 1;
        for(b = 0; b < s; ++b) {
            for(c = 0; c < s; ++c) {
                if(a[c] < a[c + 1]) {
                    temp = a[c];
                    a[c] = a[c + 1];
                    a[c + 1] = temp;
                }
            }
        }
    }


    public static boolean isSorted(int[] a) {
        for(int i = 0; i < a.length-1; i++) {
            if(a[i] > a[i + 1]) {
                return false;   
            }
        }
        return true;        
    }

    public static void isort(int a[]) {
        for(int i = 1; i < a.length; i++){
            int j = i;
            int b = a[i];
            while(j > 0 && a[j - 1] > b) {
                a[j] = a[j - 1];
                j--;
            }
            a[j] = b;
        }
    }       

}

测试班&#34;标准&#34;是:

public class BinarySearchTestSuite {

    private BinarySearchTestSuite() {}

    static int tot = 0;
    static int pass = 0;
    static int nonPass = 0;
    static int ecc = 0;

    public static void main(String[] args) {

        int[] a1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int[] a2 = {};

        int x1 = 5;
        int x2 = 0;
        int x3 = 10;

        System.out.println();
        System.out.println("---- Test method find ----");

        //Test n.1      
        try {
            tot++;
            System.out.print("Test n.1 - Array: [ ");
            for(int i = 0; i < a1.length; i++)
                System.out.print(a1[i] +  " ");
            System.out.println("]. Element to find: " + x1 + ".");
            if(a1[BinarySearch.find(x1, a1)] == x1) {
                System.out.println(x1 + " is in position " + BinarySearch.find(x1, a1) + ".");
                System.out.println("Test OK.");
                pass++;
            }
            else if(BinarySearch.find(x1, a1) == -1) {
                System.out.println(x1 + " is not present in array");
                System.out.println("TTest OK.");
                pass++;   
            } 
            else {
                System.out.println("Test FAIL.");
                nonPass++;
            } 
        } catch(Exception eccezione) {
            System.out.println("Test FAIL.");
            ecc++;
        }
        System.out.println();

        //Test n.2
        try {
            tot++;
            System.out.print("Test n.2 - Array: [ ");
            for(int i = 0; i < a1.length; i++)
                System.out.print(a1[i] +  " ");
            System.out.println("]. Element to find: " + x2 + ".");
            if(a1[BinarySearch.find(x2, a1)] == x2) {
                System.out.println(x2 + " is in position " + BinarySearch.find(x2, a1) + ".");
                System.out.println("Test OK.");
                pass++;
            }
            else if(BinarySearch.find(x1, a1) == -1) {
                System.out.println(x1 + " is not present in array");
                System.out.println("Test OK.");
                pass++;   
            }   
            else {
                System.out.println("Test FAIL.");
                nonPass++;
            } 
        } catch(Exception eccezione) {
            System.out.println("Test FAIL.");
            ecc++;
        }
        System.out.println();  

        //RESULT
        System.out.println();    
        System.out.println("Test totali: " + tot);
        System.out.println("Test andati a buon fine: " + pass);   
        System.out.println("Test falliti: " + nonPass);
        System.out.println("Test falliti con lancio di una eccezione: " + ecc);         

    } 
}

如何使用JUnit创建测试类? 我需要一些简单的例子。

我知道在测试类中我必须编写这段代码:

private final ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
private final ByteArrayOutputStream errBuffer = new ByteArrayOutputStream();

@Before
public void setupOutputStreams() {
    System.setOut(new PrintStream(outBuffer));
    System.setErr(new PrintStream(errBuffer));
}

@After
public void cleanupOutputStreams() {
    System.setOut(null);
    System.setErr(null);
}

在这段代码之后,我如何编写单独测试的代码? 然后我正常编译并运行这个文件(BinarySearchTest.java)?或者有另一种方法可以做到这一点? 我有点困惑......

谢谢!

由于

1 个答案:

答案 0 :(得分:1)

在JUnit4中编写单元测试非常简单:编写一些使用代码的小方法,并使用JUnit assertions确保代码产生您期望的答案。

@RunWith(JUnit4.class) // JUnit4.class is a "runner".
public class BinarySearchTest {
  // By convention, the test for class Foo is named FooTest. You can name the
  // test anything you'd like, though, especially if you split your test for
  // Foo into more than one file.

  @Test public void isSortedShouldReturnTrueWhenSorted() { // Same with methods.
    assertTrue(BinarySearch.isSorted(new int[] { 2, 4, 6 }));
  }

  @Test public void isSortedShouldReturnFalseWhenUnsorted() {
    assertFalse(BinarySearch.isSorted(new int[] { 4, 2, 6 }));
  }

  @Test public void isSortedShouldReturnTrueWhenEmpty() {
    assertTrue(BinarySearch.isSorted(new int[] {}));
  }

  // Write more tests here!
}

虽然many IDEs have built-in ways of running JUnit tests,但您也可以run tests from the command line。您不必编写main方法,也不必计算通过和失败的测试,或打印错误消息; JUnit将自己处理它。相反,你运行JUnit,告诉它在哪里找到你的测试用例,JUnit运行它。

java -cp /usr/share/java/junit.jar org.junit.runner.JUnitCore your.package.BinarySearchTest
#    ^ classpath includes JUnit    ^ you're running JUnitCore ^ on your test class

对于您拥有的每个类,对于使用@Test注释的每个方法,JUnit将创建测试类的新实例,运行每个@Before - 带注释的方法,运行@Test注释方法,然后运行每个@After - 带注释的方法。对于简单的测试,您可能没有任何注释@Before@After的方法,这很好。

您的测试用例的组织主要由您决定。有些人喜欢编写一个包含许多assertTrueassertEquals语句(等)的测试方法,而其他人则更喜欢编写许多小问题,每个测试用例都解决不同的问题(如上所述)。这取决于你,但请记住,在第一个断言失败或抛出任何异常之后,JUnit将停止测试任何给定的方法,因此使用许多较小的方法可以让您更好地了解究竟是什么错误。沿着这些方向,特定的方法名称是有用的:您永远不会自己调用它们,并且让JUnit报告isSortedShouldReturnFalseWhenUnsorted失败可能比跟踪isSortedWorks可能失败的原因要容易得多。

  • 您可以在org.junit.Assert文档页面上查找所有断言。请注意,它们是different than the assert keyword。您还可以编写自己的代码,以便在出错时抛出异常。
  • 不要担心setOutsetErr。虽然重定向那些将在测试写入stdout和stderr的模块时获得更清晰的测试输出,但是你的默认情况下并不这样做,而且JUnit也不介意。