2015-05-18 103 views
1

我有豆:常規斯波克嘲諷彈簧自動裝配豆

@Service 
public class EQueueBookingService { 

    @Autowired 
    public EQueueBookingClient eQueueBookingClient; 

我嘗試寫一些測試使用斯波克這個bean EQueueBookingService。 https://code.google.com/p/spock/wiki/SpockBasics

我假裝是

class EQueueBookingServiceTest extends Specification { 

@Autowired 
EQueueBookingService testedService; 

EQueueBookingClient eQueueBookingClient = Mock(EQueueBookingClient); 

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

和測試方法:

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

def result = testedService.cancelBooking(request); 

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

爲什麼eQueueBookingClient不嘲笑?

當我調試它:在測試 - 我看到模擬實例,當我去方法 - 我看到真正的bean實例。

非常感謝!

回答

0

我找到解決方案!

需要實現二傳手這個客戶端,並使用它設置,如:

private EQueueBookingClient eQueueBookingClient = Mock(EQueueBookingClient); 

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

如果定義了服務客戶爲公共和使用=這是行不通的; 例如:

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