2012-09-09 119 views
1

我在visual studio(2010)中創建了一個非常非常簡單的領域層。然後我使用新的測試嚮導來創建一個基本的單元測試。但是,當我嘗試使用使用聲明,以便我可以測試我的代碼..它說我的命名空間無法找到...這是我第一次使用visual studio,所以我對我在做什麼感到不知所措錯誤。命名空間無法識別?

我的代碼

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace Home 
{ 
    class InventoryType 
    { 

     /// <summary> 
     /// Selects the inventory type and returns the selected value 
     /// </summary> 
     public class InventorySelect 
     { 
      private string inventoryTypes; 
      public String InventoryTypes 
      { 
       set 
       { 
        inventoryTypes = value; 
       } 

       get 
       { 
        return inventoryTypes; 
       } 
      } 


      /// <summary> 
      /// Validate that the inventory is returning some sort of value 
      /// </summary> 
      /// <returns></returns> 
      public bool Validate() 
      { 
       if (InventoryTypes == null) return false; 
       return true; 
      } 
     } 
    } 
} 

我的測試代碼

using System; 
using System.Text; 
using System.Collections.Generic; 
using System.Linq; 
using Microsoft.VisualStudio.TestTools.UnitTesting; 
using Home.InventoryType.InventorySelect; 

namespace HomeTest 
{ 
    [TestClass] 
    public class TestInventoryTypeCase 
    { 
     [TestMethod] 
     public void TestInventoryTypeClass() 
     { 
      InventorySelect select = new InventorySelect(); 
      select.inventoryTypes = "Collection"; 

      if (Validate() = true) 
       Console.WriteLine("Test Passed"); 
      else 
       if (Validate() = false) 
        Console.WriteLine("Test Returned False"); 
       else 
        Console.WriteLine("Test Failed To Run"); 

      Console.ReadLine(); 

     } 
    } 
} 
+1

如果(驗證()= true)可以更簡單地寫爲IF(驗證() ) –

回答

2

我假設你的測試類是處於自己的項目,所以你需要添加一個引用到該項目。 (使用聲明不添加引用,它僅允許您在代碼中使用類型而不完全限定其名稱。)

+0

修復它無法找到使用聲明,謝謝。但它仍然無法找到驗證或InventorySelect等? – Expecto

+0

Validate()是InventorySelect類中的一個方法,所以就Validate()而言,您不能簡單地單獨調用該方法。您已使用「InventorySelect select = new InventorySelect();」行實例化了一個InventorySelect,因此您需要使用「select.Validate()」。 –

2

聲明InventoryType類作爲public

InventorySelect類可以private,而不是public

+0

好的,但是這並不能改變我的測試類不能識別我的Home命名空間的事實,讓我無法運行它? – Expecto

4

使用引用一個命名空間,而不是特定的類(除非爲類名添加別名)。您的使用聲明應僅包含「主頁」一詞。

using Home.InventoryType.InventorySelect; 
//becomes 
using Home; 

這裏是MSDN的鏈接上使用的指令:using Directive (C#)

1

當您在解決方案中創建「多項目」時(通過向項目添加項目任何現有的解決方案),項目不瞭解彼此。

在解決方案資源管理器中轉到您的測試項目並在「參考」下,右鍵單擊並選擇「添加參考」。然後選擇「項目」選項卡,您將能夠添加項目對測試項目的引用。

此外,請確保您將項目中的類定義爲「public」,以便能夠在測試項目中訪問它們。

namespace Home 
{ 
    public class InventoryType 
    { 
      ... 
    } 
} 

注意,你仍然需要在你的C#測試類的頂部的 「使用」 的文章:

using Home; 

namespace HomeTest 
{ 
    public class TestInventoryTypeCase 
    { 
      ... 
    } 
}