2014-12-02 37 views
2

我是編程和c#的新手,並且已經被分配了爲遺留代碼編寫單元測試的任務,以準備進行大的數據庫更改。單元測試WinForms

我在單元測試中讀得越多,我對自己的方法就越懷疑。

您將如何處理爲以下內容寫入單元測試? 目前我只是單元測試我的數據訪問層方法,確保他們返回結果?但顯然單元測試應該獨立於任何外部環境?

當幾乎所有東西都在調用數據庫或存儲過程時,如何測試我的應用程序?

我的表單代碼:

public void button1_Click(object sender, EventArgs e) 
{ 
    LoadAllCountries() 
} 

private static void LoadAllCountries() 
{ 
    List<nsHacAppMod.ViewCountryInfo> oReturn = moBusinessServices.GetAllCountries(); 
} 

我的數據訪問層這個代碼

public List<nsAppMod.ViewCountryInfo> GetAllCountries() 
{ 
    List<nsAppMod.ViewCountryInfo> oReturn; 

    var oResult = from c in moDataContext.ViewCountryInfos 
        select c; 

    oReturn = oResult.ToList(); 

    return oReturn; 
} 

我目前的單元測試,這是可以接受的?如果不是,你會測試什麼?

[Test] 
public void LoadAllCountries() 
{ 
    hac.CatalogSamples cs = new hac.CatalogSamples(); 
    var countries = cs.GetAllCountries().count(); 

    Assert.GreaterOrEqual(countries 0); 
} 
+1

當你運行你測試你得到了什麼..這更是一個自以爲是的問題,因爲不是每個人都寫'單元測試Code'的同樣的方式..赫克我不知道有多少開發人員甚至每天寫它無論如何我沒有看到任何錯誤,但我猶豫是否在我的產品環境中的'斷言'編碼親自你GOOGLE和最佳實踐關於單元測試..?我會在做單元測試時寫三種類型的測試'負面的,肯定的和例外的# – MethodMan 2014-12-02 20:26:55

+3

單元測試的重要之處在於你試圖「證明」某些東西。你目前的測試「證明」什麼? ('cs.GetAllCountries'將返回0個或更多記錄)這些信息是否有用? – 2014-12-02 20:26:56

+3

您需要爲您的數據訪問方法進行集成測試(測試使用外部資源(即數據庫)),然後您的單元測試只是確保在正確位置調用集成測試方法 – reggaeguitar 2014-12-02 20:27:30

回答

1

您可以單元測試數據訪問的事情,如果你的背景是基於去像IContext的接口可以僞造的,然後你可以測試只是你的代碼試圖測試像GetAllCountries()方法。

但是,除了try catch之外,沒有實際的邏輯來測試。我看起來就像這樣:如果它是一個沒有邏輯的屬性或方法,那麼它就不值得測試。使用像FakeItEasy嘲弄的框架 我將測試這種方法就像這樣:

public class ClassToTest 
{ 
    internal virtual MoDataContext CreateContext() 
    { 
     return new MoDataContext(); 
    } 

    public List<ViewCountryInfo> GetAllCountries() 
    { 
     List<ViewCountryInfo> oReturn = null; 

     try 
     { 
      var oResult = from c in this.CreateContext().ViewCountryInfos 
          select c; 

      oReturn = oResult.ToList(); 
     } 
     catch (Exception) 
     { 
     } 

     return oReturn; 
    } 

    [Fact] 
    public void Test_GetAllCountries_ResultCountShouldBeGreaterThan0() 
    { 
     var fakeData = new List<ViewCountryInfo>(); 
     fakeData.Add(new ViewCountryInfo()); 

     var sut = A.Fake<ClassToTest>(); 
     A.CallTo(sut).CallsBaseMethod(); 
     A.CallTo(() => sut.CreateContext()).Returns(fakeData); 

     var result = sut.GetAllCountries(); 

     Assert.IsTrue(result.Count() > 0); 
    } 
+1

我想提到的其他事情之一是假冒東西或測試靜態方法真的很難。 – 2014-12-02 22:29:54