【问题标题】:mock a CrudRepository findById ("111").get ()模拟一个 CrudRepository findById("111").get()
【发布时间】: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


【解决方案1】:

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

在您的场景中,您试图在依赖方法的结果上模拟对 get() 的调用,即 findById()。所以根据 Mockito 的规则 findById() 仍然返回 null 因为你没有存根

你需要的是这个

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 2014-04-02
    • 2020-02-23
    • 2021-04-26
    • 1970-01-01
    • 2019-12-16
    • 2017-08-21
    相关资源
    最近更新 更多