如何忽略传递给被模拟方法的参数 [英] how to ignore the argument passed to a method being mocked

查看:54
本文介绍了如何忽略传递给被模拟方法的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Mockito 测试我的 scalaplay 代码.我的代码使用一个 save 方法,它接受一个 User 参数.我不关心传递给 save 的值.我尝试将这种行为编码如下

I am testing my scala and play code using Mockito. My code uses a save method which takes a User argument. I don't care about the value passed to save. I tried to code this behaviour as follows

when(mockUserRepository.save(any())).thenReturn(Future(Some(user)))

但我收到错误

错误:(219, 36) not found: value anywhen(mockUserRepository.save(any())).thenReturn(Future(Some(user)))

mockito中为scala代码指定any的方法是什么?

What is the way to specify any for scala code in mockito?

在我的 build.sbt 中.我只下载了 mockito-core.我还需要别的东西吗?

In my build.sbt. I have downloaded only mockito-core. Do I need something else as well?

"org.mockito" % "mockito-core" % "2.24.5" % "test"

推荐答案

您可以使用 org.mockito.Matchers

import org.mockito.Mockito._
import org.mockito.Matchers._

val mockUserRepository = mock[call_your_MockUserRepositiry_service] 
    // something like below 
    // val service = mock[Service[Any, Any]] OR
    // val mockService = mock[MyService]

when(mockUserRepository.save(any)) thenReturn(Future(Some(user)))

请参考 https://www.programcreek.com/scala/org.mockito.Matchers

更新:

如果 Mockito 2.0 中不推荐使用 Matchers 那么你可以使用 org.mockito.ArgumentMatchers

If Matchers are deprecated in Mockito 2.0 then you can use org.mockito.ArgumentMatchers

Java 中类似下面的代码

class Foo{
    boolean bool(String str, int i, Object obj) {
        return false;
    }
}

Foo mockFoo = mock(Foo.class);
when(mockFoo.bool(anyString(), anyInt(), any(Object.class))).thenReturn(true);

在 Scala 中类似下面的代码

def setupService(inputResponse: Future[Unit]): AdminService = {
    val mockConnector = mock[MongoConnector]

    when(mockConnector.putEntry(ArgumentMatchers.any(), ArgumentMatchers.any())(ArgumentMatchers.any()))
      .thenReturn(inputResponse)

    new AdminService(mockConnector)
  }

希望有帮助!

这篇关于如何忽略传递给被模拟方法的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆