首页 > 解决方案 > Junit5 测试字符串列表错误答案

问题描述

我不知道为什么即使列表相同,测试也会失败 [13] [, abc, Abjh45, ch1, 5662, ch2, ch3, ch4, ch5], abc ✘ 预期:listes.PureListString@5b94b04d<[, abc, Abjh45, ch1, 5662, ch2, ch3, ch4, ch5, abc]> 但为:listes.PureListString@8c3b9d<[, abc, Abjh45, ch1, 5662, ch2, ch3, ch4, ch5, abc]>

在此处输入图像描述

这是我的 addLast() 方法的代码

    public PureListString addLast(String elt) {
        PureListString newCell = new PureListString(elt);
        PureListString head = new PureListString(this.first);
        PureListString tmp = this;
        if (tmp == EMPTY_LIST)
        {
            return newCell;
        }
        newCell = tmp.tail.addLast(elt);
        head.tail = newCell;
        head.size = tmp.size + 1;
        return head;
    }

这是构造函数


    public PureListString(String elt) {
        this.first = elt;
        this.tail = EMPTY_LIST;
        this.size = 1;
    }

这是我的平等方法

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof PureListString)) {
            return false;
        }
        PureListString p = (PureListString) obj;
        if (size() != p.size()) {
            return false;
        }
        if (!isEmpty() && !p.isEmpty()){
            if (getFirst() != p.getFirst())
            {
                return false;
            }
            return removeFirst() == p.removeFirst();
        }
        for (int i = 0; i < size(); i++) {
            if (get(i) != p.get(i))
            {
                return false;
            }
        }
        return true;
    }

测试方法

    public final void testAddLast(PureListString self, String elt) {
        assumeTrue(self != null);
        // Invariant
        assertInvariant(self);

        // préconditions
        assumeTrue(elt != null);

        // Purity
        saveState(self);

        // Exécution
        PureListString result = self.addLast(elt);

        // Post conditions
        assertNotNull(result);
        assertNotSame(result, self);
        assertEquals(result.getLast(), elt);
        assertTrue(result.size() == (self.size() + 1));
        for (int i = 0; i < self.size(); i++) {
            assertEquals(self.get(i), result.get(i));
        }
        if (self.isEmpty()) {
            assertEquals(result.getFirst(), elt);
            assertTrue(result.removeFirst().isEmpty());
        } else {
            assertEquals(result.getFirst(), self.getFirst());
            assertEquals(result, self.removeFirst().addLast(elt).addFirst(self.getFirst()));
        }

        // Purity
        assertPurity(self);

        // Invariant
        assertInvariant(self);
    }

请注意,我无法更改测试方法。

标签: java

解决方案


推荐阅读