如何JUnit测试ArrayList.remove()

时间:2015-11-05 11:41:00

标签: java arraylist junit

您好我正在尝试在JUnit中测试ArrayList的remove方法:

class SomeClass {
    constructor(){
        this.v1 = 1;
        this.v2 = 2;
    }

    a() {
        return new Promise((resolve, reject) => {
            console.log('a', this.v1);  // Do something with `this`
            resolve();
        });
    }

    b(obj) {
        return new Promise((resolve, reject) => {
            console.log('b', obj.v2);   // Do something with `this`
            resolve();
        });
    }

    c() {
        return this.a().then(this.b(this));   // passing b as argument
    }
}

const sc = new SomeClass();

sc.c().then(() =>{
    console.log('done')
}).catch((error) => {
    console.log('error', error);
});

所以我只是检查ArrayList的大小是否减少了一个,这有点原始,所以我实验室的导师告诉我,最好使用反射返回删除的项目,以便制作确保我们删除了正确的项目,我不知道该怎么做。

非常感谢任何帮助。

4 个答案:

答案 0 :(得分:0)

我认为你的方法是合理的,但我还会在之前验证状态:

@Test
public void testRemoveCommentValidIndex(){
    assertEquals("Before the remove", 3, item.getNumberOfComments());
    item.removeComment(2);
    assertEquals("Remove the comment", 2, item.getNumberOfComments());
}

答案 1 :(得分:0)

你可以这样做:

@Test
 public void testRemoveCommentValidIndex() 
{

    Comment commentThatShouldBeRemoved = new Comment();
    //now set values of that comment in order to be equal to comment that 
    //will be removed

    Comment commentRemoved = item.removeComment(2);
    assertEquals("Remove the comment", 2, item.getNumberOfComments());
    assertEquals("Comment removed", commentThatSHouldBeRemoved, commentRemoved);
}

答案 2 :(得分:0)

如果您在ArrayList上使用remove(int),它将返回从集合中删除的对象。你不应该使用反射来做这样的事情。您可以使用我引用的方法或只是迭代列表并检查每个成员。反思是巨大的过度杀伤。

答案 3 :(得分:0)

你可以用Hamcrest库做更好的断言。在此链接中:How do I assert a List contains elements with a certain property?解释了如何检查对象是否包含在ArrayList中。