2011-06-12 38 views
0

我在JUnit中测试assertArrayEquals时遇到这个问题,因为我不确定它是如何工作的。我创建了一个方法,所以我可以理解它,但它不工作。任何人都可以在这里帮助排序了这一点是代码:assertArrayEquals testing

public class ArrayAssert 
{ 

    public boolean check(int[] arr2) 
    { 

     final int[] arr1 = new int[] { 1, 2, 3 }; 
     arr2 = new int[arr1.length]; 

     for (int i = 0; i < arr1.length; i++) 
     { 

      if (arr1[i] != arr2[i]) 
      { 
       System.out.println("false"); 
       return false; 
      } 

     } 

     System.out.println("true"); 
     return true; 

    } 

    public static void main(String[] args) 
    { 
     // TODO Auto-generated method stub 

     Scanner scan = new Scanner(System.in); 
     ArrayAssert obj = new ArrayAssert(); 
     int[] arr2 = new int[2]; 

     for (int i = 0; i < 2; i++) 
     { 
      System.out.println("Enter numbers to check"); 
      arr2[i] = scan.nextInt(); 
      obj.check(arr2); 
     } 
    } 
} 

下面是测试情况下,我使用JUnit

import static org.junit.Assert.*; 

import org.junit.Test; 

public class ArrayAssertTest { 

int []val = new int[]{1,2,3}; 

    @Test 
public void testCheck(int[] val) { 
    boolean expect = true; 
    boolean result ; 

    assertArrayEquals(expect,result); 
} 



} 

回答

0

在您的测试代码“期望”和“结果”应该是充满阵列制成本身。

有关详细信息,请参阅JUnit Assert API了解方法参数。

+0

为什么我必须这样做?我使用val []数组填充数组。因此我正在检查数组是否与另一个数组相等 – Splitter 2011-06-12 12:57:16

+0

我将JUnit API中的assertMethod链接添加到答案中。评论的答案是,这是它打算使用的方式。 – Omnaest 2011-06-12 13:00:33

0

我简化你的代码一点点 这里是我想测试类:

public class ArrayAssert { 

public int[] create(){ 
    int [] array = {1,2,3}; 
    return array; 
} 
} 

,这里是我的其他类:

import static org.junit.Assert.*; 

import org.junit.Test; 

public class ArrayAssertTest { 
int []val = new int[]{1,2,3}; 

@Test 
    public void testCheck() { 

    ArrayAssert sample = new ArrayAssert(); 
    assertArrayEquals(val, sample.create()); 
} 
} 

有代码中的2个问题我注意到: 第一:任何测试不能采取任何参数 第二:assertArrayEquals只接受数组作为参数,您的参数是布尔值,如果它们是布尔数组,它将会很好。

我希望代码和解释清楚。

0

结帐Hamcrest,其中有很多内置的断言检查数组,集合等