简体   繁体   中英

groovy spock mocking spring autowired beans

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM