Ambuj Jauhari
Ambuj Jauhari

Reputation: 1299

Spock stub matching partial arguments

I am using spock for my test cases and I am stubbing a class as below, inventryDAO has a method getUser which accepts a argument of type PersistableKey.

In the main code the argument is created as below

PersistableKey userKey = new PersistableKey(1)
userKey.setRepresentedObjectClass(User.class);

In my Specification if I write the stub and argument as below, it works fine

User collUser = new User(1);
InventoryDAO inventoryDAO = Stub()

PersistableKey userKey = new PersistableKey(1)
userKey.setRepresentedObjectClass(User.class);

inventoryDAO.getUser(userKey) >> collUser

But what I really want to do is to be able to pass argument without setting the setRepresentedObjectClass, something like this

User collUser = new User(1);
InventoryDAO inventoryDAO = Stub()
    
PersistableKey userKey = new PersistableKey(1)
    
inventoryDAO.getUser(userKey) >> collUser

Is it possible to match the argument based on partial values ?

Upvotes: 4

Views: 4785

Answers (1)

Leonard Brünings
Leonard Brünings

Reputation: 13222

Spock supports several kind of Argument Constraints, when you use an object you are using the Equality Constraint which uses groovy equality to compare the constraint argument with the argument from an invocation. If you can't or don't want to change the equals method of PersistableKey, then you can manually compare the fields that are relevant to you using a Code Argument Constraint.

inventoryDAO.getUser({ userKey.id == 1 }) >> collUser

You can also combine a Code Argument Constraint with a Type Constraint

inventoryDAO.getUser({ userKey.id == 1 } as PersistableKey) >> collUser

Upvotes: 9

Related Questions