The following test creates error when I test tuples.
'Assert.AreEqual(test,productRepository.GetById(1))' threw an exception of type 'NUnit.Framework.AssertionException'
Many solutions presented below require an override equals function for each model. This is very hard to maintain for software with 200+ models in project. Is there any Nuget package or auto code generator which will create equality override methods for all the 200 models?
These all ask to override
- How to Compare two objects in unit test?
- C# - Asserting two objects are equal in unit tests
- c# How to find if two objects are equal
NUnit Test
[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);
}
Repository
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);
}
}
Model
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; }
}