简体   繁体   中英

assertArrayEquals testing

I have this problem in testing assertArrayEquals in JUnit as I am not sure how it works. I created a method so I can understand it but its not working. Can anyone help sort this out here is the code:

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

Here is the test case I made using 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);
}



}

"expect" and "result" in your test code should be the filled arrays itself.

See the JUnit Assert API for the method parameters for more details.

I simplified your code a little bit Here is the class that I want to test:

public class ArrayAssert {

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

and here is my other class:

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

there were 2 problems in your code that I noticed: first: any test cant take any parameters second: assertArrayEquals only takes arrays as parameters, your parameters were booleans, it would have been just fine, if they were boolean array.

I hope the code and explanation makes it clear.

Checkout Hamcrest , which has lots of built in assertion checks for arrays, collections, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM