2014-04-19 4 views
1

정수 배열의 이진 검색과 관련된 몇 가지 방법이 포함 된 Java 클래스가 있습니다. 이제이 메소드의 정확성을 검증하는 새로운 클래스를 만들어야하며,이 메소드를 다른 배열과 찾을 다른 요소로 테스트하십시오. 지금은 "표준"방식으로 수행 한 새로운 클래스의 테스트이지만 JUnit을 사용할 수 있음을 알고 있습니다. 인터넷에서 몇 가지 쉬운 가이드를 검색했지만 많이 이해하지 못했습니다. BinarySearch.java "주"내 클래스가이 방법으로 만든 경우JUnit에 대한 의문과 제안

예를 들어, "표준"테스트 클래스는

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

} 

입니다

:

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)을 컴파일하고 실행하십시오. 아니면 다른 방법이 있을까요? 조금 혼란 스럽네요 ...

고마워!

감사 단위 테스트 JUnit4에서 쉽게 작성

+0

Junit 통합에 사용하는 IDE를 확인하십시오. 기본적으로 Junit 테스트를 실행하는 자체 프로그램을 작성하지 않지만 클래스를 확장하고 @Test로 테스트 메소드에 주석을 추가하고 Junit이 당신을위한 레그 워크를 수행하도록합니다. – TeTeT

+0

[Unit Test 작성 방법] 가능한 복제본 (http://stackoverflow.com/questions/8751553/how-to-write-a-unit-test) – Joe

답변

1

: 코드를 사용하는 몇 가지 작은 방법을 쓰기 및 코드 당신이 기대하고있는 답변을 생산하도록 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이이를 실행합니다. 당신이, 당신이 @Test와 주석 모든 방법을 위해, JUnit을 당신의 @Test -annotated 방법을 실행, 모든 @Before -annotated 방법을 실행, 테스트 클래스의 새 인스턴스를 만듭니다이 각 클래스

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 

다음 모든 실행 @After - 주석 방법. 간단한 테스트를 위해 @Before 또는 @After 주석이 달린 메소드가 없을 수도 있습니다.

테스트 케이스의 구성은 주로 결정할 사항입니다. 어떤 사람들은 많은 assertTrue 또는 assertEquals 문장을 가진 하나의 테스트 메소드를 쓰는 것을 좋아하지만 다른 사람들은 다른 aspect를 다루는 많은 작은 테스트 케이스를 작성하는 것을 선호한다. 그것은 당신에게 달려 있지만, JUnit은 첫 번째 어설 션이 실패하거나 예외가 발생 된 후에 주어진 메소드 테스트를 중단하므로 많은 작은 메소드를 사용하면 정확히 무엇이 잘못되었는지 더 잘 알 수 있습니다. 그 라인을 따라 특정 메서드 이름이 도움이됩니다. 직접 호출하지 않고 isSortedShouldReturnFalseWhenUnsorted이 실패했다는 JUnit보고를하면 isSortedWorks이 실패하는 이유를 추적하는 것보다 훨씬 쉽습니다.

  • org.junit.Assert 문서 페이지에서 모든 주장을 조회 할 수 있습니다. 그들은 different than the assert keyword입니다. 오류에 대한 예외를 던지는 코드를 작성할 수도 있습니다.
  • setOutsetErr에 대해 걱정할 필요가 없습니다. stdout과 stderr에 쓰는 모듈을 테스트 할 때 그것들을 리다이 렉팅하면 더 깨끗한 테스트 결과를 얻을 수 있지만, 기본적으로 그렇게하지는 않는다. JUnit은 상관 없다.