模拟CrudRepository findById(“ 111”)。get()

sas*_*kab 4 java spring spring-data spring-data-jpa spring-boot

我需要从测试类中模拟Spring crudRepository findById(“ 111”)。get()

我的代码如下所示,即使我按照以下步骤操作,它也会返回null。

(1)我需要测试我的Service类,并创建了serviceTest类,并使用了mokito和powermock

(2)有一个方法,我需要让User给一个ID,其中服务类方法只是调用存储库findById(“ 111”)。get()并返回User对象

(3)修改这样的测试方法

//configuration codes working well
.
.
.
tesst123 () {
.
.
//here some code working well
.
.
.
when (mockRepository.findById("111").get()).thenReturn (new User());

}
Run Code Online (Sandbox Code Playgroud)

在上面,我可以嘲笑模拟存储库,并在调试时显示创建的对象。

但是,如果我在调试时评估了mockRepository.findById(“ 111”)部分,它将返回null

如果我在调试时评估了mockRepository.findById(“ 111”)。get()部分,它将返回nullPointer异常

****最后我播下.get()方法返回Optional.class,它是最终类

那么有什么方法可以模拟这种情况?

eke*_*iga 7

您要模拟的方法返回一个Optional对象。默认情况下,当您不进行模拟/存根时,Mockito返回返回类型的默认值,即对象引用为null(在您的情况下包括Optional),或者为基元提供适用的值,例如int为0。

在您的方案中,您尝试模拟依赖方法(即findById())的结果对get()的调用。因此,根据Mockito的规则,findById()仍返回null,因为您没有将其存根

你需要的是这个

tesst123 () {
   //some code as before
   User userToReturn = new User(); 
   when(mockRepository.findById("111")).thenReturn(Optional.of(userToReturn));
   //verifictions as before
 }
Run Code Online (Sandbox Code Playgroud)