groovy spock mocking spring autowired beans

旧巷老猫 提交于 2019-12-11 11:25:02

问题


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


来源:https://stackoverflow.com/questions/30303706/groovy-spock-mocking-spring-autowired-beans

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!