字符串缓冲单元测试失败



我正在尝试创建钻石,然后返回将字符串转换为字符串的字符串。在控制台中,我看到了我的期望。但是我的单位测试失败了。请阐明我的测试为什么失败。

public class Diamond {
    public static String print(int n) {
        if (n <= 0)
            return null;
        StringBuffer buffer = new StringBuffer();
        int mid = (n + 1) / 2;
        int midIdx = mid - 1;
        int run = 1;
        while (run <= n) {
            char[] chars = new char[n];
            int delta = Math.abs(mid - run);
            for (int idx = 0; idx < mid - delta; idx++) {
                chars[midIdx - idx] = '*';
                chars[midIdx + idx] = '*';
            }
            buffer.append(rightTrim(new String(chars)) + "n");
            run++;
        }
        return buffer.toString();
    }
    public static String rightTrim(String s) {
        int i = s.length() - 1;
        while (i >= 0 && s.charAt(i) != '*') {
            i--;
        }
        return s.substring(0, i + 1);
    }
    // public static void main(String... strings) {
    // System.out.println(print(3));
    // }
}

单元测试 导入静态org.junit.assert.assertequals; 导入静态org.junit.assert.assertnull;

import org.junit.Test;
public class DiamondTest {
    @Test
    public void testDiamond3() {
        StringBuffer expected = new StringBuffer();
        expected.append(" *n");
        expected.append("***n");
        expected.append(" *n");
        assertEquals(expected.toString(), Diamond.print(3));
    }
    @Test
    public void testDiamond5() {
        StringBuffer expected = new StringBuffer();
        expected.append("  *n");
        expected.append(" ***n");
        expected.append("*****n");
        expected.append(" ***n");
        expected.append("  *n");
        assertEquals(expected.toString(), Diamond.print(5));
    }
    @Test
    public void getNullReturned() {
        assertNull(Diamond.print(0));
    }
}

chars数组未初始化(char[] chars = new char[n];(。因此,非*字符与空间(' '(不同,即数组中包含null字节。初始化数组有助于,例如使用Arrays.fill(chars, ' ')

问题在这里。

char[] chars = new char[n];

您是从字符数组中初始化一个字符串,默认情况下为u0000(零值(。

在测试中,您正在与太空字符进行比较(ASCII值32(。

因此,您需要用空格初始化字符串。这是一种做到这一点的方法:

char[] chars = new char[n];
Arrays.fill(chars, ' ');

最新更新