Testing arguments of method execution with Spock Framework

Testing arguments of method execution with Spock Framework

methodArgTesting value returned from a method is easy. Each basic tutorial of unit testing covers that. Checking if a specific method has been executed at all is not that simple but possible. In this post, I show how to check if a particular method was executed with a certain argument. All of this is presented in Spock Framework.


 I have a method to test:

public Long addAppleToBasket(Long basketId, double weight) throws EmployeeNotFoundException {
Basket basket = basketsRepository.findOne(basketId);
if (basket == null) {
throw new BasketNotFoundException();

Apple apple = new Apple(weight);

return apple.getId();

Honestly, in real life it is not a good candidate to test as there is not much of business logic, but that is not the point of this article. It is just an example.

I am not interested in testing the returned value - an ID as it is a sequential number with no business value. But the most important is what was saved in the repository.

A unit test in Spock Framework looks like this:

def "test addAppleToBasket"() {
Basket basket = Mock()
basketsRepository.findOne(3) >> basket

basketService.addAppleToBasket(3, 0.123)
1 * basketsRepository.save(_) >> { arguments ->
final Apple apple = arguments.get(0)
assert apple == new Apple(weight: 0.123) }

1 * method means that the method is expected to be executed with any argument (_) exactly once during the test. The second part tells Spock that the first argument of the method should be an object of the Apple class. The assertion line is a concise way to instruct Spock to check what the argument really should be. In this case, it should be an apple with weight = 0.123.

Would you like to learn Liquibase? Enroll to my course on Udemy.

Promo code: LIQUIBASE_2021

liquibase course promo