gpt4 book ai didi

c# - 使用最小起订量模拟 EF DbContext

转载 作者:IT王子 更新时间:2023-10-29 03:46:36 24 4
gpt4 key购买 nike

我正在尝试使用模拟的 DbContext 为我的服务创建单元测试。我创建了一个界面 IDbContext具有以下功能:

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

我的真实上下文实现了这个接口(interface)IDbContextDbContext .

现在我正在尝试模拟 IDbSet<T>在上下文中,所以它返回一个 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());
}

我总是在 .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

最佳答案

我设法通过创建 FakeDbSet<T> 来解决它实现 IDbSet<T> 的类

public class FakeDbSet<T> : IDbSet<T> where T : class
{
ObservableCollection<T> _data;
IQueryable _query;

public FakeDbSet()
{
_data = new ObservableCollection<T>();
_query = _data.AsQueryable();
}

public virtual T Find(params object[] keyValues)
{
throw new NotImplementedException("Derive from FakeDbSet<T> and override Find");
}

public T Add(T item)
{
_data.Add(item);
return item;
}

public T Remove(T item)
{
_data.Remove(item);
return item;
}

public T Attach(T item)
{
_data.Add(item);
return item;
}

public T Detach(T item)
{
_data.Remove(item);
return item;
}

public T Create()
{
return Activator.CreateInstance<T>();
}

public TDerivedEntity Create<TDerivedEntity>() where TDerivedEntity : class, T
{
return Activator.CreateInstance<TDerivedEntity>();
}

public ObservableCollection<T> Local
{
get { return _data; }
}

Type IQueryable.ElementType
{
get { return _query.ElementType; }
}

System.Linq.Expressions.Expression IQueryable.Expression
{
get { return _query.Expression; }
}

IQueryProvider IQueryable.Provider
{
get { return _query.Provider; }
}

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _data.GetEnumerator();
}

IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return _data.GetEnumerator();
}
}

现在我的测试看起来像这样:

[TestMethod]
public void TestGetAllUsers()
{
//Arrange
var mock = new Mock<IDbContext>();
mock.Setup(x => x.Set<User>())
.Returns(new FakeDbSet<User>
{
new User { ID = 1 }
});

UserService userService = new UserService(mock.Object);

// Act
var allUsers = userService.GetAllUsers();

// Assert
Assert.AreEqual(1, allUsers.Count());
}

关于c# - 使用最小起订量模拟 EF DbContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25960192/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com