【问题标题】:JUnit test case for array used for concatenations用于连接的数组的 JUnit 测试用例
【发布时间】:2019-07-12 08:14:49
【问题描述】:

这是我尝试为它编写 junit 测试用例的数组代码的串联,但它给出了语法错误。我不确定确切的语法是什么。

public static String[] concatArray(String[] firstArry, String[] secArry) {
        if (null != firstArry && null == secArry) {
            return firstArry;
        } else if (null == firstArry && null != secArry) {
            return secArry;
        } else if( null != firstArry && null != secArry ){
            String[] concatArry = new String[firstArry.length + secArry.length];
            System.arraycopy(firstArry, 0, concatArry, 0, firstArry.length);
            System.arraycopy(secArry, 0, concatArry, firstArry.length, secArry.length);
            return concatArry;
        }else{
            return null;
        }

JUnit 测试用例。

@Test
    public void testConcatArray() {
        String[] arr1 = {"nodename", "nodecategory"};
        String[] arr2 = {" test"," case"};

        Assert.assertEquals({"abc"}, StringUtils.concatArray(arr1, arr2));
    }

【问题讨论】:

标签: java junit


【解决方案1】:

编译器不知道第一个参数的实际类型是什么。

您需要将以下内容与不同的断言一起使用:

Assert.assertArrayEquals(new String[]{"abc"}, StringUtils.concatArray(arr1, arr2));

【讨论】:

  • 它的返回对象是因为 junit 测试用例失败
  • 不要认为在没有类型声明的情况下甚至是允许的
【解决方案2】:

您可以使用assertArrayEquals() 方法断言数组。

见:Using assertArrayEquals in unit tests

也许您想看看 Java Stream API afaik 它还可以处理 null 数组的串联,因此您不必关心 null 处理。 例如如果您有一个数组 ['abc'] 和 null,则 Stream concat 将返回 ['abc']。 (但也许你需要在我不确定 100% 之前进行过滤:yourStream.filter(array -> array != null))

看看这个以更好地理解我的意思:

https://www.concretepage.com/java/jdk-8/java-8-concat-streams-lists-sets-arrays-example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    相关资源
    最近更新 更多