how to ignore the argument passed to a method bein

2019-08-16 08:32发布

问题:

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)))

but I get error

Error:(219, 36) not found: value any when(mockUserRepository.save(any())).thenReturn(Future(Some(user)))

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

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"

回答1:

You can use 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)))

Please refer https://www.programcreek.com/scala/org.mockito.Matchers

Update:

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

In Java Something like below

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);

In Scala something like below

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

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

    new AdminService(mockConnector)
  }

Hope it helps!



回答2:

Try any[User] instead of any()



回答3:

I'd say that to avoid this and many other issues related to Scala-Java interoperability, you should use the Scala version of Mockito (mockito-scala) with it, after mix-in the trait org.mockito.ArgumentMatchersSugar you can write

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

Or if you fancy a more scala-like syntax

mockUserRepository.save(*) shouldReturn Future(Some(user))

Check the readme to see more examples and scala specific features



标签: scala mockito