C#Nuget或AutoCode Generator在单元测试中比较多个对象

时间:2018-10-18 20:38:03

标签: c# unit-testing asp.net-core nunit asp.net-core-2.0

以下测试在测试元组时会产生错误。

  

'Assert.AreEqual(test,productRepository.GetById(1))'引发了类型为'NUnit.Framework.AssertionException'的异常

下面介绍的许多解决方案都要求每个模型都具有覆盖等值函数。对于项目中具有200多个模型的软件,这很难维护。是否有任何Nuget软件包或自动代码生成器将为所有200个模型创建相等替代方法?

这些都要求覆盖

NUnit测试

[Test]
public void TestProducts()
{
    var options = new DbContextOptionsBuilder<ElectronicsContext>()
        .UseInMemoryDatabase(databaseName: "Products Test")
        .Options;

    using (var context = new ElectronicsContext(options))
    {
        //DbContextOptionsBuilder<ElectronicsContext> context = new DbContextOptionsBuilder<ElectronicsContext>()

        context.Product.Add(new Product { ProductId = 1, ProductName = "TV", ProductDescription = "TV testing", ImageLocation = "test" });
        context.SaveChanges();
        ProductRepository productRepository = new ProductRepository(context);
        var test = new Product
            {ProductId = 1, ProductName = "TV", ProductDescription = "TV testing", ImageLocation = "test"};

       **//This works**
        Assert.AreEqual("TV", productRepository.GetById(1).ProductName);

       **//This Fails**
        Assert.AreEqual(test,productRepository.GetById(1));

       **//This Fails**
        Assert.AreEqual(Object.Equals(test, productRepository.GetById(1)), 1);
    }

存储库

public class ProductRepository : IProductRepository<Product>
{
    private readonly ElectronicsContext _context;
    public ProductRepository(ElectronicsContext context)
    {
        _context = context;
    }

    public IEnumerable<Product> GetAllProduct()
    {
        return _context.Product.ToList();
    }

    public IQueryable<Product> Products => _context.Product;

    public Product GetById(int productid)
    {
        return _context.Product.Find(productid);

    }
}

模型

public partial class Product
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public string ProductDescription { get; set; }
    public string ImageLocation { get; set; }

    public int? ProductCategoryId { get; set; }
    public virtual ProductCategory ProductCategory { get; set; }
}

2 个答案:

答案 0 :(得分:0)

您可能应该检查返回对象的ID。如果引用指针不相等,则尝试测试类是否相同将失败。由于该框架可以使用代理,因此并非总是如此。

答案 1 :(得分:0)

尝试使用FluentAssertions nuget软件包(请参见“ Object graph comparison”部分)。

代替

Assert.AreEqual(test,productRepository.GetById(1))

您可以执行以下操作:

test.Should().BeEquivalentTo(productRepository.GetById(1));