2011-02-03 63 views
1

我想測試的屬性獲取它從一個服務調用的返回值裏面的服務,但我有麻煩嘲諷服務呼叫。犀牛製品 - 莫克的方法調用屬性

這裏是我的財產:

public ICountry Country 
    { 
     get 
     { 
      if (_country == null) 
      { 
       ICountryService countryService = new CountryService(); 
       _country = countryService.GetCountryForCountryId(_address.CountryId); 
      } 
      return _country; 
     } 
    } 

這是我嘗試在測試這個:

[TestMethod] 
    public void Country_should_return_Country_from_CountryService() 
    { 
     const string countryId = "US"; 
     _address.CountryId = countryId; 

     var address = MockRepository.GenerateStub<Address>(_address); 

     var country = MockRepository.GenerateMock<ICountry>(); 
     var countryService = MockRepository.GenerateStub<ICountryService>(); 

     countryService.Stub(x => x.GetCountryForCountryId(countryId)).IgnoreArguments().Return(country); 

     Assert.AreEqual(address.Country, country); 
    } 

我不斷收到一個錯誤,因爲真正的countryService被調用,而不是我的嘲笑。我正在使用MsTest和Rhino Mocks。我究竟做錯了什麼?

回答

6

您的問題是,房地產直接構建依賴。由於這個模擬服務沒有被調用,實際的真正的CountryService實現被調用。

解決的辦法可能是利用CountryService工廠(或服務本身)中的其他對象(地址?)構造函數的構造函數注入。這樣,你可以得到你的假CountryService(模擬)要返回,併成爲一個由該方法

打了個比方:

private ICountryService _countryService; 

//constructor 
public OuterObject(ICountryService countryService) 
{ 
    //maybe guard clause 
    _countryService = countryService; 
} 


public ICountry Country 
{ 
    get 
    { 
     if (_country == null) 
     { 
      _country = _countryService.GetCountryForCountryId(_address.CountryId); 
     } 
     return _country; 
    } 
} 

您將需要再經過嘲笑ICountryService到其他對象在構造單元測試

+0

問題與那就是我還特意打電話國家服務來獲取即將狀態置物業,並有可能是別人。我不想依靠傳遞這些對象到類中來獲取對象。 – Martin 2011-02-03 14:39:55