有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

列出如何在java Mockito中测试子列表的相等性

我有一个将集合作为参数的方法:

call(Collection<String> strings);

我调用的方法如下:

myClass.call(list.sublist(1,n));

当我运行代码时,一切都运行得很好。 然而,在使用Mockito进行测试时,我使用的是代码片段:

verify(myClass,times(1)).call(myList);

它反复抛出以下错误:

Unable to evaluate the expression Method threw 'java.util.ConcurrentModificationException' exception.

我猜这是因为它无法进行测试。有什么办法能帮上忙吗?我想检查一下我的列表是否包含与传递的元素相同的元素


共 (2) 个答案

  1. # 1 楼答案

    我得到了答案。实际上,verify方法是在整个函数运行之后调用的

    因此,即使myClass在调用时有正确的子列表作为参数,但在以后修改列表时,子列表也会变得无效

    在调用整个方法之后调用Verify方法,因此验证时要测试的子列表无效

    因此,它抛出了这个例外

  2. # 2 楼答案

    使用@Captor并将Hamcrest添加到您的项目中,然后执行以下操作

    import org.hamcrest.Matchers.containsInAnyOrder;
    
    @RunWith(MockitoJUnitRunner.class)
    public class MyTest
    {
        MyClass myClass = new MyClass();
    
        @Captor private ArgumentCaptor<Collection<String>> collectionCaptor;
    
        @Test
        public void someTest() throws Exception
        {
            Collection<String> expectedCollection = Arrays.asList("a", "b", "c"); 
    
            // setup goes here
            // execute test
    
            Mockito.verify(myClass).call(collectionCaptor.capture());
            Collection<String> whatWasCaptured = collectionCaptor.getValue();
            assertThat(whatWasCaptured, Matchers.containsInAnyOrder(expectedCollection));
        }
    }
    

    还要确保你的收藏没有在其他线程中发生变异。如果你不能控制其他线程在做什么,那么你应该防御性地编码并返回return Collections.unmodifiableList(myList),或者将你的数据结构切换到一个支持immutablility like Guava library