2015-12-06 77 views
0

我正在編寫一個單元測試,它驗證使用正確的數據選擇了特定的產品。目前,該測試正在提供以下錯誤:單元測試 - 無法從存儲庫類訪問方法

System.NullReferenceException:未將對象引用設置爲對象的實例。

While debugging through the test, I noticed that my result variable is null... I thought I was calling my SelectProduct method correctly, but not sure what is wrong.

Additional question - Any suggestions on how to better Assert?

[TestClass] 
    public class ProductRepositoryTests 
    { 
     [TestMethod] 
     public void SelectProduct_selectProduct_productIsSelected() 
     {   
      // access ProductRepository 
      Mock<IProductRepository> mock = new Mock<IProductRepository>(); 

      // Arrange - mocked product 
      Product product1 = new Product 
      { 
       ProductId = 1, 
       ProductName = "Snicker Bar", 
       ProductPrice = .25M, 
       ProductCategory = "Candy", 
       ProductQuantity = 12 
      }; 

      // Act - select new product using SelectProduct method 
      var result = mock.Object.SelectProduct(product1.ProductId); 

      // Assert 
      Assert.AreEqual(result.ProductId, 1); 
      Assert.AreEqual(result.ProductName, "Snicker Bar"); 
      Assert.AreEqual(result.ProductPrice, .25M); 
     } 
    } 

這裏是我的庫層中的其他的代碼:

接口:

public interface IProductRepository 
{ 
    Product SelectProduct(int productId); 
} 

repository類:

public class ProductRepository : IProductRepository 
    { 
     public Product SelectProduct(int productId) 
     { 
      throw new System.NotImplementedException(); 
     } 
    } 
+0

這個測試中你的系統在測試什麼?看起來你正在測試一個模擬/假的對象,而不是真正的類。 –

+0

這是一個很好的問題@YacoubMassad ...我試圖在我的ProductRepository中測試該方法。這有幫助嗎?請記住,我還沒有實施我的SelectProduct方法,因此我可以按照TDD – ChaseHardin

回答

2

你似乎想要測試ProductRepository類,而是測試一個假對象。

這是您的測試應該如何看起來像:

// Arrange 
var sut = new ProductRepository(); //sut means System Under Test 
... 

// Act - select new product using SelectProduct method 
var result = sut.SelectProduct(product1.ProductId); 

// Assert 
.... 

假貨(或嘲弄)僅用於假貨之類的依賴性測試,而不是類本身。所以,在這個特定的測試中,你不需要使用模擬框架。

+0

非常感謝你@YacoubMassad ...一旦時間框架打開,我會將其標記爲答案...你認爲什麼我的斷言是否是測試我選擇正確產品的好方法?另外,我還有其他的依賴注入類,我需要使用模擬嗎? – ChaseHardin

+1

你的斷言是確定的。一個可能的改進是使'產品'類實現'IEquatable ',然後你可以有一個'product1'和'result'進行比較的'Assert.AreEqual'。 –

+1

如果您正在測試具有依賴關係的類,那麼您應該創建這些依賴關係的虛假/模擬並手動將它們注入到SUT構造函數中。 –