【问题标题】:JUnit test case failure. java.lang.AssertionError: expected:<[I@12c5431> but was:<[I@14b6bed>JUnit 测试用例失败。 java.lang.AssertionError: 预期:<[I@12c5431> 但是是:<[I@14b6bed>
【发布时间】:2013-09-02 17:14:55
【问题描述】:

我已经面对这个问题有一段时间了,它开始让我感到沮丧。代码需要返回最接近 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

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

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

【问题讨论】:

    标签: java


    【解决方案1】:

    您正在比较 Object 引用。要么使用Arrays.equals 比较数组内容

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

    或 JUnit assertArrayEquals

    Assert.assertArrayEquals(expected, actual);
    

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

    【讨论】:

    • 谢谢!但是在我纠正了这个错误之后,它给了我错误。有 1 次失败:1)最近的KTest(SelectorTest)数组首先在元素 [0] 处不同;预期:,但实际为:。我认为我的代码有问题。
    • 那是因为 nearestK 正在返回 [0, 1] 但您期待的是 [6, 7]
    • 您也可以使用Assert.equals(Arrays.toString(expected), Arrays.toString(actual)); 我发现错误消息提供的信息更多。 YMMV。
    【解决方案2】:

    使用

    Assert.assertArrayEquals(expected, actual);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-19
      • 1970-01-01
      • 2011-03-29
      • 1970-01-01
      • 2020-05-24
      • 2011-09-29
      • 2014-05-09
      相关资源
      最近更新 更多