2010-09-07 49 views
0

我有以下方法:正確的方式進行單元測試私有變量

private string _google = @"http://www.google.com"; 

public ConnectionStatus CheckCommunicationLink() 
{ 
    //Test if we can get to Google (A happy website that should always be there). 
    Uri googleURI = new Uri(_google); 
    if (!IsUrlReachable(googleURI, mGoogleTestString)) 
    { 
     //The internet is not reachable. No connection is available. 
     return ConnectionStatus.NotConnected; 
    } 

    return ConnectionStatus.Connected; 
} 

的問題是,我怎麼得到它不嘗試谷歌(從而避免在互聯網上成爲了依賴)的連接。

最簡單的方法是取_google並將其更改爲指向機器的本地位置。但要做到這一點,我需要製作_googlepublic。我寧願不這樣做,因爲_google不應該由應用程序改變。

我可以使`_google'成爲重載版本的方法(或對象構造函數)的參數。但是這也暴露了一個我從不希望應用程序使用的界面。其他選項是_googleinternal。但對於應用程序,internalpublic相同。所以,其他人看不到_google,應用界面仍然暴露它。

有沒有更好的方法?如果是這樣,請說明。

(另外,請不要在我的例子中挑選,除非它確實有助於找出一個解決辦法。我要求在一般情況下是這樣,不一定這個確切的例子想法。)

+0

你想測試變量,還是CheckCommunicationLink你的測試用例? – Eiko 2010-09-07 19:48:46

+0

@Eiko - 方法('CheckCommunicationLink') – Vaccano 2010-09-07 20:43:01

+1

螞蟻這個測試應該測試*究竟是什麼*?對不起,我沒有得到這個測試的意圖。這種方法似乎只能檢查互聯網是否啓動。如果你僞造這些東西,你會得到什麼信息?爲什麼麻煩測試呢? – Eiko 2010-09-07 22:26:15

回答

0

你爲什麼有_google硬編碼在您的代碼?爲什麼不把它放在一個配置文件中,然後你就可以改變你的測試例如?

0

一些選項:

  • 使從外部配置_google負載(也許提供www.google.com作爲缺省值),並提供用於單元測試一個特殊的配置;
  • 將單元測試類放入包含CheckCommunicationLink方法的類中。

注:我強烈建議讓它可配置。在現實世界中,依賴於特定第三方網站的可用性並不是一個好主意,因爲它們可以被本地防火牆等阻止。

0

對於單元測試目的,您應該模擬您正在使用的任何http連接在你的班級(這是隱藏在IsUrlReachable方法)。通過這種方式,您可以檢查您的代碼是否真的試圖連接到谷歌而無需實際連接。如果您需要更多的嘲笑幫助,請粘貼IsUrlReachable方法。

如果上述方案不是一個選項,你可以考慮有一個局部測試HTTP服務器和:

  1. 把網址配置,這樣就可以指向本地地址
  2. (這一個是討厭)使用反射測試之前改變_google
  3. (最純粹將在這裏不同意),您可以創建一個過載取參數,並使用一個用於測試(這樣你就只測試CheckCommunicationLink(string url)方法
0123對於(3)

代碼:

private string _google = @"http://www.google.com"; 

public ConnectionStatus CheckCommunicationLink() 
{ 
    return CheckCommunicationLink(_google); 
} 

public ConnectionStatus CheckCommunicationLink(string url) 
{ 
    //Test if we can get to Google (A happy website that should always be there). 
    Uri googleURI = new Uri(url); 
    if (!IsUrlReachable(googleURI, mGoogleTestString)) 
    { 
     //The internet is not reachable. No connection is available. 
     return ConnectionStatus.NotConnected; 
    } 

    return ConnectionStatus.Connected; 
} 
1

重構代碼依賴於一個ICommunicationChecker:

public interface ICommunicationChecker 
{ 
    ConnectionStatus GetConnectionStatus(); 
} 

然後你的測試(S)可以模擬這個接口使實現細節無關。

public class CommunicationChecker : ICommunicationChecker 
{ 
    private string _google = @"http://www.google.com"; 

    public ConnectionStatus GetConnectionStatus() 
    { 
     //Test if we can get to Google (A happy website that should always be there). 
     Uri googleURI = new Uri(_google); 
     if (!IsUrlReachable(googleURI, mGoogleTestString)) 
     { 
      //The internet is not reachable. No connection is available. 
      return ConnectionStatus.NotConnected; 
     } 

     return ConnectionStatus.Connected; 
    } 
} 
相關問題