首页 > 解决方案 > 如何模拟某种类型的列表

问题描述

我有控制器,它将 List 作为帖子正文

User getYoungestUser (int id,@Valid @RequestBody List<User> requests)
{
    //somelogic and returns a user 
    
   return requests.stream().min(Comparator.comparing(x-> x.getAge())).get();
    
}

我只是想嘲笑

Mockito.when(service.getYoungestUser(anyInt(),anyList()))
    .thenReturn(Collections.singletonList(new User()));
    
    

而不是anyList,我想使用像anyList(User.class) 或any(List< User >.class)这样的用户类型列表,编译器当然不接受它们,它在模拟期间严格检查列表的类型

我从其他链接获得了以下内容,但无法弄清楚如何在代码中使用它。

@SuppressWarnings( "unchecked" )
List<User> mocked1 = mock(List.class);      

我尝试了以下三种方法,但都没有奏效。请提出一种使用方法

//throws compiling error

    Mockito.when(service.getYoungestUser(anyInt(),any(mocked1)))               
        .thenReturn(Collections.singletonList(new User()));


//not working as it treats first parameter is expression and 
//second param is a value and throws error after running the test
    Mockito.when(anyInt(),service.getYoungestUser(anyInt(),mocked1)))               
        .thenReturn(Collections.singletonList(new User()));



//wont work as eq() is used for different purpose,yet just gave a try, The mock 
//doesnt work
    Mockito.when(anyInt(),service.getYoungestUser(anyInt(),eq(mocked1))))               
        .thenReturn(Collections.singletonList(new User()));

标签: javamockingmockito

解决方案


以下应该可以解决问题:

Mockito.when(service.getYoungestUser(anyInt(), ArgumentMatchers.<List<User>>anyList()))               
    .thenReturn(Collections.singletonList(new User()));

推荐阅读