单元测试 - 无法从存储库访问方法 Class

Unit Testing - Can't Access Method From Repository Class

我正在编写一个单元测试,用于验证是否选择了具有正确数据的特定产品。目前,测试提供以下错误:

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);
}

存储库Class:

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

您似乎想测试 ProductRepository class,但您却在测试一个假对象。

你的测试应该是这样的:

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

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

// Assert
....

Fakes(或 Mocks)仅用于伪造被测 class 的依赖项,而不是 class 本身。因此,在这个特定的测试中,您不需要使用模拟框架。