gpt4 book ai didi

c# - 如何为存储库设置最小起订量

转载 作者:太空宇宙 更新时间:2023-11-03 13:27:07 25 4
gpt4 key购买 nike

我有方法

public IEnumerable<string> LoadCountries()
{
try
{
return GetAll().GetCountries();
}
catch (Exception)
{
return null;
}
}

GetAll() 方法从 sql server 加载数据,但我在测试中不需要它所以我更改了 IEnumerable 客户的数据库。我想测试一下

Mock<ICustomersRepository> mock = new Mock<ICustomersRepository>();
mock.Setup(m => m.GetAll()).Returns(customers.AsQueryable()); //change data
IEnumerable<string> countries = mock.Object.LoadCountries();
Assert.AreEqual(countries.Count(), 6); //expect 6 countries

但是在这个测试中countries.Count() == 0;当然我可以修改 Mock Setup 并添加

mock.Setup(m => m.LoadCountries()).Returns(customers.AsQueryable().GetCountries());

但我不想这样做,因为我想测试的其他功能要大得多。有谁知道如何设置 GetAll() 函数返回我的测试数组,即使 GetAll() 在测试类中实现?我只是尝试设置

mock.CallBase = true;
mock.Setup(m => m.LoadCountries()).CallBase();

但我只看到异常

System.NotImplementedException: This is a DynamicProxy2 error: The interceptor attempted to 'Proceed' for method
'System.Collections.Generic.IEnumerable`1[System.String] LoadCountries()' which has no target. When calling method without target there is no implementation to 'proceed' to and it is the responsibility of the interceptor to mimic the implementation (set return value, out arguments etc).

最佳答案

您正在创建实现 ICustomersRepository 接口(interface)的动态代理类。然后你正在行使这个生成的代理:

Mock<ICustomersRepository> mock = new Mock<ICustomersRepository>();
IEnumerable<string> countries = mock.Object.LoadCountries();

这不是个好主意。你用这个测试验证了什么?代理一代?您的真实代码不会使用代理。您应该使用模拟来提供模拟依赖项,以测试您的应用程序使用的真实类。

实际上我不会测试 LoadCountries() 在内部调用 GetAll()。因为这是实现的细节,而不是客户存储库的业务需求。我会编写一些验收/集成测试来验证给定客户是否返回了正确的国家/地区。

更新:因此您的 GetCountries() 过滤器是一个扩展,那么您不需要在其测试中涉及存储库。那是一个简单的静态类,可以自行测试。 但是 不与数据库交互的测试也不会很有值(value),因为您的扩展将查询组合到数据源,数据源将由查询提供程序翻译。我给你举个例子。如果您有本地方法调用(或您的查询提供者无法翻译的方法):

public static class Extensions
{
public static IQueryable<string> GetCountries(this IQueryable<Customer> q)
{
return q.GroupBy(c => c.Country).Select(x => LocalMethod(x.Key));
}

private static string LocalMethod(string country)
{
return country.ToUpper();
}
}

然后当您使用内存中的对象时,以下单元测试将通过:

List<Customer> customers = new List<Customer> {
new Customer { Country = "USA" },
new Customer { Country = "Spain" }
};

var countries = Extensions.GetCountries(customers.AsQueryable());
Assert.AreEqual(countries.Count(), 2);

但是当您运行使用 Entity Framework 查询 SQL 数据库的应用程序时,EF 将无法将此过滤器转换为 SQL。

关于c# - 如何为存储库设置最小起订量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22040215/

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