1

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 ?

Ambuj Jauhari
  • 1,187
  • 4
  • 26
  • 46
  • I do not understand your question with the fragmentary code snippets and ambiguous explanation given. Please update the question to contain a minimal, complete, executable set of classes enabling others to reproduce your problem, instead of having to guess. Thank you. – kriegaex Jul 31 '21 at 00:01

1 Answers1

7

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
Leonard Brünings
  • 12,408
  • 1
  • 46
  • 66