我正在編寫一個單元測試,它驗證使用正確的數據選擇了特定的產品。目前,該測試正在提供以下錯誤:單元測試 - 無法從存儲庫類訪問方法
System.NullReferenceException:未將對象引用設置爲對象的實例。
While debugging through the test, I noticed that my
result
variable is null... I thought I was calling mySelectProduct
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();
}
}
這個測試中你的系統在測試什麼?看起來你正在測試一個模擬/假的對象,而不是真正的類。 –
這是一個很好的問題@YacoubMassad ...我試圖在我的ProductRepository中測試該方法。這有幫助嗎?請記住,我還沒有實施我的SelectProduct方法,因此我可以按照TDD – ChaseHardin