2011-03-16 61 views
3

我瞭解如何進行單元測試的基礎知識,但是我經常爲尋找有意義的測試項目而苦苦掙扎。我相信我必須製造一個假實施並注入消費者。我有一個服務類負責訂閱(使用Exchange Web服務(EWS))Exchange 2010,請求更新新郵件。爲了將我的訂閱實現與服務本身分開,我決定在服務中注入實現。以下是我目前擁有的。我忽略了專門與Exchange進行通信的代碼。如何爲假貨創建有意義的單元測試

// Not a big fan of having two identical interfaces... 
public interface IStreamingNotificationService 
{ 
    void Subscribe(); 
} 

public interface IExchangeService 
{ 
    void Subscribe(); 
} 

public class StreamingNotificationService : IStreamingNotificationService 
{ 
    private readonly IExchangeService _exchangeService; 

    public StreamingNotificationService(IExchangeService exchangeService) 
    { 
     if (exchangeService == null) 
     { 
      throw new ArgumentNullException("exchangeService"); 
     } 

     _exchangeService = exchangeService; 
    } 

    public void Subscribe() 
    { 
     _exchangeService.Subscribe(); 
    } 
} 

public class ExchangeServiceImpl : IExchangeService 
{ 
    private readonly INetworkConfiguration _networkConfiguration; 
    private ExchangeService ExchangeService { get; set; } 

    public ExchangeServiceImpl(INetworkConfiguration networkConfiguration) 
    { 
     if (networkConfiguration == null) 
     { 
      throw new ArgumentNullException("networkConfiguration"); 
     } 

     _networkConfiguration = networkConfiguration; 
     // Set up EWS 
    } 

    public void Subscribe() 
    { 
     // Subscribe for new mail notifications. 
    } 
} 

更具體地說,我該如何創建一個有意義的單元測試來確保訂閱以它應該的方式工作?

回答

3

通常你會使用一個模擬框架來創建一個假的交換和測試這個對象,這個對象實際上被稱爲。我通常使用Rhino Mocks,你的測試看起來像例如像這樣(有很多方法來實現它):

[Test] 
public void SubscribesToExchange() 
{ 
    var exchange = MockRepository.GenerateMock<IExchangeService>(); //this is the stub 
    var service = StreamingNotificationService(exchange); //this is the object we are testing 

    service.Subscribe(); 
    service.AssertWasCalled(x => x.Subscribe();); 
} 
1

解耦和注入在單元測試方面總是一個非常好的主意。

現在您可以輕鬆測試您的StreamingNotificationService類。所有你需要做的就是測試是否構造表現良好,以及如果subscribemethod調用你的注入(和假的)IExchangeService。

相關問題