gpt4 book ai didi

unit-testing - 使用某些 linq 表达式 (moq) 调用了验证方法

转载 作者:行者123 更新时间:2023-12-04 04:05:41 25 4
gpt4 key购买 nike

无法弄清楚语法。

//class under test
public class CustomerRepository : ICustomerRepository{
public Customer Single(Expression<Func<Customer, bool>> query){
//call underlying repository
}
}

//test

var mock = new Mock<ICustomerRepository>();
mock.Object.Single(x=>x.Id == 1);
//now need to verify that it was called with certain expression, how?
mock.Verify(x=>x.Single(It.Is<Expression<Func<Customer, bool>>>(????)), Times.Once());

请帮忙。

最佳答案

嗯,您可以通过为具有与 lambda 参数匹配的方法的接口(interface)创建模拟并验证以下内容来验证是否正在调用 lambda:

public void Test()
{
var funcMock = new Mock<IFuncMock>();
Func<Customer, bool> func = (param) => funcMock.Object.Function(param);

var mock = new Mock<ICustomerRepository>();
mock.Object.Single(func);

funcMock.Verify(f => f.Function(It.IsAny<Customer>()));
}

public interface IFuncMock {
bool Function(Customer param);
}

以上可能对你有用,也可能对你不起作用,这取决于 Single方法与表达式一起使用。如果该表达式被解析为 SQL 语句或被传递到 Entity Framework 或 LINQ To SQL,那么它会在运行时崩溃。但是,如果它对表达式进行了简单的编译,那么您可能会侥幸成功。

我谈到的表达式编译看起来像这样:
Func<Customer, bool> func = Expression.Lambda<Func<Customer, bool>>(expr, Expression.Parameter(typeof(Customer))).Compile();

编辑 如果您只是想验证是否使用某个表达式调用了该方法,则可以匹配表达式实例。
public void Test()
{

Expression<Func<Customer, bool>> func = (param) => param.Id == 1

var mock = new Mock<ICustomerRepository>();
mock.Object.Single(func);

mock.Verify(cust=>cust.Single(func));
}

关于unit-testing - 使用某些 linq 表达式 (moq) 调用了验证方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3458406/

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