【问题标题】:Using hamcrest matchers with primitive type arrays将 hamcrest 匹配器与原始类型数组一起使用
【发布时间】:2013-08-21 19:33:38
【问题描述】:

由于自动装箱和拆箱,Hamcrest 适用于原始数据类型,就像在这种情况下:

assertThat(1, is(1));

但是,我想将 hamcrest 的 hasItemInArray 匹配器与这样的原始类型数组一起使用:

int[] values = someMethodCall();
assertThat(values, hasItemInArray(1));

由于原始数据类型的数组没有自动装箱/拆箱,因此上述代码无法编译。除了手动从int[] 转换为Integer[] 之外,是否有任何首选方式来完成上述操作?

【问题讨论】:

    标签: java testing hamcrest


    【解决方案1】:

    AFAIK 没有自动的方法来实现这一点。如果您可以使用第 3 方库,您可能需要查看 Apache Commons Lang 库,它提供了一个带有转换方法的 ArrayUtils 类:

    Integer[] toObject(int[] array)

    int[] values = someMethodCall();
    Integer[] objValues = ArrayUtils.toObject(values);
    assertThat(objValues , hasItemInArray(1));
    

    【讨论】:

    • 我已经猜到了,但感谢您的确认并将我指向 Apache Commons!
    【解决方案2】:

    这是我的解决方案,它也使用 Apache Commons ArrayUtils#toObject

    进口

    import static org.apache.commons.lang3.ArrayUtils.toObject;
    import static org.hamcrest.MatcherAssert.assertThat;
    import static org.hamcrest.Matchers.arrayContaining;
    import static org.hamcrest.Matchers.arrayContainingInAnyOrder;
    import static org.hamcrest.Matchers.hasItemInArray;
    import static org.hamcrest.Matchers.is;
    import static org.hamcrest.Matchers.not;
    

    您可以编写可读的测试,例如

    @Test
    void primitiveArrayTest() {
        int[] actual = new int[]{1, 2, 3};
    
        assertThat(toObject(actual), is(arrayContaining(1, 2, 3)));
        assertThat(toObject(actual), is(arrayContainingInAnyOrder(2, 3, 1)));
        assertThat(toObject(actual), hasItemInArray(2));
        assertThat(toObject(actual), is(not(arrayContaining(-5))));
    }
    

    is 只是为了提高可读性。

    【讨论】:

      【解决方案3】:

      然而,编写自己的匹配器的另一种方法是在匹配器库中使用一个匹配器,例如 conmatch

      int[] values = someMethodCall();
      assertThat(values, intArrayContaining(1));
      

      我猜 github 上已经有其他 Matchers 可用了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-04
        • 1970-01-01
        相关资源
        最近更新 更多