Java 具有相同返回类型的方法的Mockito默认行为和自定义行为
假设我有以下代码通过模拟Java 具有相同返回类型的方法的Mockito默认行为和自定义行为,java,unit-testing,reflection,junit,mockito,Java,Unit Testing,Reflection,Junit,Mockito,假设我有以下代码通过模拟UserService来测试UserController(其中UserController引用了UserService): 导入静态org.mockito.mockito.mock; 导入静态org.mockito.mockito.when; ... 公共类UserControllerTest{ private final List users1=new ArrayList(); private final List users2=new ArrayList(); @以前
UserService
来测试UserController
(其中UserController
引用了UserService
):
导入静态org.mockito.mockito.mock;
导入静态org.mockito.mockito.when;
...
公共类UserControllerTest{
private final List users1=new ArrayList();
private final List users2=new ArrayList();
@以前
公共用户(){
用户=新用户();
用户设置ID(1L);
users1.add(用户);
用户=新用户();
user.setId(2L);
users2.add(用户);
}
@试验
public void testFindAlls()引发异常{
UserService UserService=mock(UserService.class);//第1行
当(userService.findAll1()).thenReturn(users1);//行2
when(userService.findAll2()).thenReturn(users2);//第3行
UserController UserController=新的UserController();
ReflectionTestUtils.setField(userController,“userService”,userService);
List users3=userController.findAll1();//line4
List users4=userController.findAll2();//line5
...
}
}
我有以下疑问:
userService.findAll1()
和userService.findAll2()
的默认行为是什么userService.findAll1()
和userService.findAll2()
返回相同的结果类型(List
)。第3行是否会覆盖第2行中定义的行为?我的意思是,将userService.findAll1()
返回users2
而不是users1
when
方法签名是public static ongoingstubing when(T methodCall)
因此示例中的T
将是类型为List
的元素,其值可能为null
。那么,when
方法如何确定不同的调用作为参数传递另一方面:
您可能不需要使用反射将模拟放入对象中。查看@InjectMocks&@Mock。因此,您可以使用它们(或如何使用它们)取决于您的JUnit和Mockito版本。
()我的意思是,when方法签名是
public static ongoingstubing when(T methodCall)
因此示例中T
将是List
类型的元素,其值可能为null
。那么,when方法是如何确定不同的调用作为参数传递的呢?我已经更新了答案,希望它能帮助您了解java语言的某些功能以及mockito实际上在做什么。如果您想更深入地了解mockito实现,您可能希望自己签出mockito实现,但如果您只想编写一些测试,则不必签出mockito实现。将上一次编辑替换为在这块板上找到的更详细的答案非常感谢,这正是我想要的!
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
...
public class UserControllerTest {
private final List<User> users1 = new ArrayList<>();
private final List<User> users2 = new ArrayList<>();
@Before
public void initUsers() {
User user = new User();
user.setId(1L);
users1.add(user);
User user = new User();
user.setId(2L);
users2.add(user);
}
@Test
public void testFindAlls() throws Exception {
UserService userService = mock(UserService.class); //line1
when(userService.findAll1()).thenReturn(users1); //line2
when(userService.findAll2()).thenReturn(users2); //line3
UserController userController = new UserController();
ReflectionTestUtils.setField(userController, "userService", userService);
List<User> users3 = userController.findAll1(); //line4
List<User> users4 = userController.findAll2(); //line5
...
}
}