JUnit 测试用例失败。java.lang.AssertionError: 预期:<[I@12c5431> 但是是:<[I@14b6bed>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18578071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:10:05  来源:igfitidea点击:

JUnit test case failure. java.lang.AssertionError: expected:<[I@12c5431> but was:<[I@14b6bed>

java

提问by catchwisdom

I have been facing this problem for a while and it starts frustrating me. The code needs to return the k elements of a nearest to val. This method will throw an IllegalArgumentException if k is negative and return an array of zero length if k == 0 or if k > a.length. When I run the test case against this method, it reports:

我已经面临这个问题一段时间了,它开始让我感到沮丧。代码需要返回最接近 val 的 k 个元素。如果 k 为负数,则此方法将抛出 IllegalArgumentException,如果 k == 0 或 k > a.length,则返回长度为零的数组。当我针对此方法运行测试用例时,它报告:

There was 1 failure:
1) nearestKTest(SelectorTest)
java.lang.AssertionError: expected:<[I@12c5431> but was:<[I@14b6bed>
       at SelectorTest.nearestKTest(SelectorTest.java:21)

FAILURES!!!
Tests run: 1,  Failures: 1

I know this means expected didn't match actual. I just could not figure it out. :(

我知道这意味着预期与实际不符。我只是想不通。:(

public static int[] nearestK(int[] a, int val, int k) {
  int[] b = new int[10];
  for (int i = 0; i < b.length; i++){
     b[i] = Math.abs(a[i] - val);
  }
  Arrays.sort(b);      
  int[] c = new int [k];
  for (int i = 0; i < k; i++){
     if (k < 0){
        throw new IllegalArgumentException("k is not invalid!");
     }
     else if (k == 0 || k > a.length){
     return new int[0];}
     else{
     c[i] = b[i];}   
  }
  return c;   
}


Test case:

import org.junit.Assert;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;


public class SelectorTest {


   /** Fixture initialization (common initialization
    *  for all tests). **/
   @Before public void setUp() {
   }


   /** A test that always fails. **/
   @Test public void nearestKTest() {
    int[] a = {2, 4, 6, 7, 8, 10, 13, 14, 15, 32};
    int[] expected = {6, 7};
    int[] actual = Selector.nearestK(a, 6, 2);
    Assert.assertEquals(expected,actual);
   }
}

采纳答案by Reimeus

You're comparing Objectreferences. Either use Arrays.equalsto compare array content

你在比较Object参考。要么用于Arrays.equals比较数组内容

Assert.assertTrue(Arrays.equals(expected, actual));

or the JUnit assertArrayEquals

或 JUnit assertArrayEquals

Assert.assertArrayEquals(expected, actual);

as suggested by @Stewart. Obviously the latter is simpler.

正如@Stewart 所建议的那样。显然后者更简单。

回答by Stewart

Use

Assert.assertArrayEquals(expected, actual);