Java 如何JUnit测试ArrayList.remove()

Java 如何JUnit测试ArrayList.remove(),java,arraylist,junit,Java,Arraylist,Junit,您好,我正在尝试在JUnit中测试ArrayList的删除方法: @Test public void testRemoveCommentValidIndex() { item.removeComment(2); assertEquals("Remove the comment", 2, item.getNumberOfComments()); } 所以我只是检查ArrayList的大小是否减小了一个,这有点原始,所以我实验室的导师告诉我,最好使用反射返回删除的项,以确保我

您好,我正在尝试在JUnit中测试ArrayList的删除方法:

@Test
 public void testRemoveCommentValidIndex() 
{

   item.removeComment(2);
    assertEquals("Remove the comment", 2, item.getNumberOfComments());

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


非常感谢您的帮助。

我认为您的方法是合理的,但我会在以下情况之前进一步验证状态:

@Test
public void testRemoveCommentValidIndex(){
    assertEquals("Before the remove", 3, item.getNumberOfComments());
    item.removeComment(2);
    assertEquals("Remove the comment", 2, item.getNumberOfComments());
}
您可以这样做:

@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);
}

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

使用Hamcrest库可以做得更好。在此链接中:解释如何检查ArrayList中是否包含对象。

Er,您是否尝试过javadocs
ArrayList.remove()
返回删除的项。是否有任何东西反对对remove返回的项调用list.contains()?问题是item.removeComment(index)方法无效,我不允许更改它,因此Comment commentRemoved=item.removeComment(2);不起作用它说不兼容的类型,void不能转换为CommentWell,如果你的方法返回void而你不能更改它,恐怕没有解决方案,即使是反射。这是一些实验室会话的问题,因此他们不允许你更改代码,通过使用您的代码并添加一些反射,我得出以下结论:public void testRemoveCommentValidIndex()抛出异常{Comment Comment Comment=new Comment(“Vandal Savage”,“很好”,3);Field Field=item.getClass().getDeclaredField(“comments”);Field.setAccessible(true);Comment Comment commentToRemove=(Comment)field.get(2);item.removeComment(2);assertEquals(“Comment removed”,Comment,commentToRemove);assertEquals(“The coment removed”,2,item.getNumberOfComments());}虽然我仍然不能这样做:Comment commentRemoved=item.removeComment(2);所以我不确定我的说法是否完全正确。你认为呢?谢谢你的帮助,我真的很感激。