当前位置:网站首页>Simulate EF dbcontext with MOQ - mocking EF dbcontext with MOQ

Simulate EF dbcontext with MOQ - mocking EF dbcontext with MOQ

2022-07-04 08:56:00 Zafo

problem :

I'm trying to create a unit test for my service with a mocked DbContext. I'm trying to use simulated DbContext Create unit tests for my service .I created an interface IDbContext with the following functions: I created an interface with the following functions IDbContext

public interface IDbContext : IDisposable{    IDbSet<T> Set<T>() where T : class;    DbEntityEntry<T> Entry<T>(T entity) where T : class;    int SaveChanges();}

My real context implements this interface IDbContext and DbContext . My real context implements this interface IDbContext and DbContext .

Now I'm trying to mock the IDbSet<T> in the context, so it returns a List<User> instead. Now I'm trying to simulate in context IDbSet<T> , So it goes back to List<User> .

[TestMethod]public void TestGetAllUsers(){    // Arrange    var mock = new Mock<IDbContext>();    mock.Setup(x => x.Set<User>())        .Returns(new List<User>        {            new User { ID = 1 }        });    UserService userService = new UserService(mock.Object);    // Act    var allUsers = userService.GetAllUsers();    // Assert    Assert.AreEqual(1, allUsers.Count());}

I always get this error on .Returns : I always get this mistake .Returns

The best overloaded method match for'Moq.Language.IReturns<AuthAPI.Repositories.IDbContext,System.Data.Entity.IDbSet<AuthAPI.Models.Entities.User>>.Returns(System.Func<System.Data.Entity.IDbSet<AuthAPI.Models.Entities.User>>)'has some invalid arguments

Solution :

Reference resources : https://stackoom.com/en/question/1kvQm
原网站

版权声明
本文为[Zafo]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202141443134738.html

随机推荐