NSubstitute 新手,在模拟采用谓词的方法调用的返回时遇到困难。 例如我在主代码中有这个
var currReport = this.ClientRepo.Get<Report>(x => x.Uid == reportUid).FirstOrDefault();
我想在测试中做这样的事情
var parentReport = new Report(){Uid = request.ParentReportUid, Name = "Test"};
this.clientRepository.Get(Arg.Is<Expression<Func<Report, bool>>>(expr => Lambda.Eq(expr, i => i.Uid == request.ParentReportUid))).Returns(new List<Report>() { parentReport }.ToArray());
这不起作用。我已经确认 request.ParentReportUid 与实际方法调用中的 reportUid 匹配。但它仍然返回一个空值。如果我切换到 Arg.Any 那么它会返返回告,如下所示
this.clientRepository.Get(Arg.Any<Expression<Func<Report, bool>>>()).Returns(new List<Report>() { parentReport }.ToArray());
这是我试图模拟的实际方法的签名。
T[] Get<T>(System.Linq.Expressions.Expression<Func<T, bool>> predicate = null);
请指教。 谢谢
最佳答案
尝试使用 NSubstitute 类 Arg public static T Is<T>(Expression<Predicate<T>> predicate)
方法。
您没有在谓词中指定类型 X 是什么。
我已经投入了一些时间,并且已经有一个解决方案。这是一个 Neleus.LambdaCompare Nuget 包。您可以使用 Lambda.Eq 方法。我已经尝试过并且效果很好。 在您的示例中,它应该类似于:
this.Repo.Get<Report>(Arg.Is<Expression<Func<Report, bool>>>(expr => Lambda.Eq(expr, i => i.ParentType == "1AType" && i.OwnerUid == 5))).Returns(reports);
这是我尝试过的示例,测试结果为绿色。此示例与您的签名相符。
public class ExpresionClass : IExpresionClass
{
T[] IExpresionClass.Get<T>(Expression<Func<T, bool>> predicate)
{
throw new NotImplementedException();
}
}
public interface IExpresionClass
{
T[] Get<T>(Expression<Func<T, bool>> predicate = null);
}
public interface ITestClass
{
Person[] GetPerson();
}
public class Person
{
public string ParentType { get; set; }
public int OwnerUid { get; set; }
}
public class TestClass : ITestClass
{
private readonly IExpresionClass expressionClass;
public TestClass(IExpresionClass expressionClass)
{
this.expressionClass = expressionClass;
}
public Person[] GetPerson()
{
var test = expressionClass.Get<Person>(x => x.ParentType == "1AType" && x.OwnerUid == 10);
return test;
}
}
[TestMethod]
public void DoesLinqMatch()
{
var person = new Person();
person.OwnerUid = 59;
person.ParentType = "ParentType";
Person[] personsarray = new Person[] { person };
var expressionClass = Substitute.For<IExpresionClass>();
expressionClass.Get(Arg.Is<Expression<Func<Person, bool>>>(expr => Lambda.Eq(expr, i => i.ParentType == "1AType" && i.OwnerUid == 10))).Returns(personsarray);
var cut = new TestClass(expressionClass);
var persons = cut.GetPerson();
persons.First().ParentType.Should().Be("ParentType");
}
关于c# - 如何在谓词参数上使用 NSubstitute 返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57034445/