【发布时间】:2018-08-29 13:47:15
【问题描述】:
我需要从我的测试类中模拟 Spring crudRepository findById("111").get()
我的代码如下所示,即使我按照以下步骤操作,它也会返回 null。
(1) 我需要测试我的 Service 类,我创建了 serviceTest 类并使用了 mokito 和 powermock
(2) 有方法,我需要让用户提供一个 id 服务类方法只是调用存储库 findById("111").get () 并返回用户对象
(3) 像这样模拟测试方法
//configuration codes working well
.
.
.
tesst123 () {
.
.
//here some code working well
.
.
.
when (mockRepository.findById("111").get()).thenReturn (new User());
}
在上面我可以模拟 mockRepository 并在调试时显示创建的对象。
但如果我在调试时评估 mockRepository.findById("111") 部分,它会返回 null
如果我在调试时评估 mockRepository.findById("111").get() 部分,它会返回 nullPointer 异常
**** 最后我播种 .get() 方法返回 Optional.class 并且它是最终类
那么有什么方法可以模拟这种场景吗?
【问题讨论】:
-
您要模拟的方法的声明是什么?
-
需要更多上下文 - 显示代码。
-
类 MyServiceImple { @AutoWire CustomRepository customRepository;公共用户 getUserByGivingId (String id) { return customRepository.findById (id).get (); } }
标签: java spring spring-boot spring-data spring-data-jpa