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

basketsRepository.save(apple);
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"() {
given:
Basket basket = Mock()
basketsRepository.findOne(3) >> basket

when:
basketService.addAppleToBasket(3, 0.123)
then:
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.

Do not miss valuable content. You will receive a monthly summary email. You can unsubscribe anytime.

We use cookies

We use cookies on our website. Some of them are essential for the operation of the site, while others help us to improve this site and the user experience (tracking cookies). You can decide for yourself whether you want to allow cookies or not. Please note that if you reject them, you may not be able to use all the functionalities of the site.