user3529850
user3529850

Reputation: 976

spock, mock a method response in a spring bean

I have an integration test written in groovy (spock) in spring boot application. One of the application beans is called Validator it has the follwoing method:

public void validateIssueDates(final List<Timestamp> issueDates) {
    issueDates.forEach(issueDate -> {
        final Timestamp now = Timestamp.valueOf(LocalDateTime.now());

        if (issueDate.before(now)) {
            throw new IllegalArgumentException("Issue date is before current date");
        }
    });
}

In the Validator class there are other methods. In my spock integration test I would like to mock response for that particular method only. In the following way:

Validator.validateIssueDates(_) >> null

I want other validations to take place, but not this one. Bascially I want to achieve this but with spock. I would like to eliminate the validateIssueDates() method from being executed

Upvotes: 0

Views: 1951

Answers (1)

user3529850
user3529850

Reputation: 976

solution using Spock

It's done using [@SpringSpy][2].
First we annotate field with a spring bean we want to wrap in spy object. For example:

@SpringSpy
private CarValidator carValidator; 

then in our test, in then part we define how we want to override method from a a bean/spy:

then:
    3 * carValidator.validateIssueDates(_) >> null

Solution using Mockito (as an additional approach, it's not related to spock solution)

I have got that pretty easy using spy in Mockito. Despite many trials (and errors) with spock's spy, It just doesn't want to work. If I get that, I post it here. For now, I can only share Mockito solution:

@Profile("test")
@Configuration
public class BeanConfig {

    @Bean
    @Primary
    public CarValidator getCarValidatorSpy(CarValidator validator) {
        CarValidator carValidatorSpy = Mockito.spy(validator);

        Mockito.doNothing().when(carValidatorSpy).validateIssueDates(Mockito.any(CarDto.class));
        return carValidatorSpy;
    }
}

That's all. Seems fairly straightforward.

Upvotes: 2

Related Questions