groovy spock mocking spring autowired beans

2019-08-10 01:11发布

问题:

I have bean:

@Service
public class EQueueBookingService {

    @Autowired
    public EQueueBookingClient eQueueBookingClient;

And I try to write some test for this bean EQueueBookingService using Spock. https://code.google.com/p/spock/wiki/SpockBasics

My mock is

class EQueueBookingServiceTest extends Specification {

@Autowired
EQueueBookingService testedService;

EQueueBookingClient eQueueBookingClient = Mock(EQueueBookingClient);

def setup() {
    testedService.eQueueBookingClient = eQueueBookingClient;
}

and test method:

...
setup:
CancelBookingResponse response = new CancelBookingResponse();
...
eQueueBookingClient.cancelBooking(_, _) >> response;
when:

def result = testedService.cancelBooking(request);

then:
result != null && result.bookId == bookId

Why eQueueBookingClient doesn't mock?

When I debug it: in test - I see Mock instance, when I go to method - I see real bean instance.

Thanks a lot!

回答1:

I've found solution!

need implement setter for this client and use it in setup like:

private EQueueBookingClient eQueueBookingClient = Mock(EQueueBookingClient);

    def setup() {
            testedService.setBookingClient(eQueueBookingClient);
        }

If define client in service as public and use = it doesn't work; For example:

testedService.eQueueBookingClient = eQueueBookingClient;//mocked instance doesn't work