mercredi 29 juillet 2020

Setup add function in Mock DbSet with Moq (Entity Framework)

I'm new to mocking, and I'm trying to create a mock DbContext for testing select, add, update, delete.

The mock for selecting is working, but when I'm trying to add the 'add' function in the setup, I'm getting the following error in my return value .Returns((CalculatieInput t) => t):

Cannot implicitly convert type 'DK.Infrastructure.CalculatieInput' to 'Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<DK.Infrastructure.CalculatieInput>

Test.cs:

    [Fact]
    public void Add1()
    {
        var context = CreateDbContext();
        _da = new CalculatieInputDA(context.Object);

        CalculatieInput item = new CalculatieInput() { Title = "add test" };

        _da.Add(item);

        List<CalculatieInput> list = _da.getAll();

        Assert.Equal(27, list.Count);
    }

    private Mock<dieKeureWebContext> CreateDbContext()
    {
        var data = GetFakeData().AsQueryable();

        var dbSet = new Mock<DbSet<CalculatieInput>>();
        dbSet.As<IQueryable<CalculatieInput>>().Setup(m => m.Provider).Returns(data.Provider);
        dbSet.As<IQueryable<CalculatieInput>>().Setup(m => m.Expression).Returns(data.Expression);
        dbSet.As<IQueryable<CalculatieInput>>().Setup(m => m.ElementType).Returns(data.ElementType);
        dbSet.As<IQueryable<CalculatieInput>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());

        dbSet.Setup(x => x.Add(It.IsAny<CalculatieInput>())).Returns((CalculatieInput t) => t);

        var context = new Mock<dieKeureWebContext>();
        context.Setup(c => c.CalculatieInput).Returns(dbSet.Object);

        return context;
    }

    private IEnumerable<CalculatieInput> GetFakeData()
    {
        var i = 1;
        var data = A.ListOf<CalculatieInput>(26);
        data.ForEach(x => x.Id = i++);
        return data.Select(_ => _);
    }

CalculatieInputDA.cs:

    public CalculatieInput Add(CalculatieInput item)
    {
        _context.CalculatieInput.Add(item);
        _context.SaveChanges();

        return item;
    }

Can someone point me in the right direction how to fix this?

Aucun commentaire:

Enregistrer un commentaire