Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scalamock mocking java interface method varargs

I need to mock a method with varargs from a java interface

public interface MyClient {
    MyResponse indexPrivileges(IndexPrivilege... parameters);
}

and I am mocking it with

(mockMyClient.indexPrivileges _).expects(*).returns(response)

but get an error

[error] /projects/lib-scala-projects/src/test/scala/com/example/MyManagerTest.scala:67: value expects is not a member of com.example.parameters.IndexPrivilege* => com.example.MyResponse
[error]       (mockMyClient.indexPrivileges _).expects(*).returns(response)
[error]                                        ^

Also, I tried with passing a Seq of IndexPrivilege to no avail

(mockMyClient.indexPrivileges _).expects(privileges).returns(response)

Any ideas?

like image 815
rojanu Avatar asked Oct 29 '22 23:10

rojanu


1 Answers

Working with Scalamock 4.1.0, there's a few possibilities that I'm aware of to make this work.

The first one is using the MatchAny matcher in the expects method. This would look like (mockMyClient.indexPrivileges _).expects(new MatchAny()).returns(response). This will allow anything that is passed to the mock (from documentation Matcher that matches everything). The downside to this approach, is that it matches everything.

The second approach is to use ArgThat matcher. ArgThat, is a Matcher that uses provided predicate to perform matching. Which means that you can perform whatever validation you'd like on the input to your function. Say you just want to check that all values of IndexPrivilege is passed to the function, you could write the test like:

val indexPrivilegeLengthValidation = new ArgThat[mutable.WrappedArray[IndexPrivilege]](
                (irArray: mutable.WrappedArray[IndexPrivilege]) => irArray.length == IndexPrivilege.values.length,
                None
            )
(mockMyClient.indexPrivileges_).expects(indexPrivilegeLengthValidation).returns(response)

I'm confident that there are other ways to approach mocking varargs, but these two approaches have worked well for me in the past.

like image 120
cahilltr Avatar answered Nov 15 '22 12:11

cahilltr