简体   繁体   English

起订量表达式<Func<> &gt;

[英]Moq Expression<Func<>>

Im trying to mock Expression<Func<>> exactly how it should work in class that im testing.我试图模拟Expression<Func<>>在我测试的课程中它应该如何工作。

My original declaration of this method looks like this:我对这个方法的原始声明如下所示:

var entity = await _repository.GetByIdAsync(input.Id1, x => x.Id2 == "Some String");

Now i want to mock that method using Moq :现在我想使用Moq模拟该方法:

// Arrange
entity.Id2 = "Some id";

// Act
_rRepositoryMock.Setup(x =>
    x.GetByIdAsync(
        It.Is<string>(y => y == input.Id1),
        It.Is<Expression<Func<MyEntity, object>>>(z => z.Id2 == "Some id")))
.ReturnsAsync(entity);

From Moq code i get this error, that Expression<Func<>> does not contein definition of Id2 .Moq代码我得到这个错误, Expression<Func<>>不包含Id2定义。

How to Mock in Moq Expression<Func<>> to work exatly as i want to in original implementation?如何在Moq Expression<Func<>>模拟以按照我想要的原始实现方式工作?

EDIT编辑

When i type something like:当我输入以下内容时:

It.Is<Expression<Func<MyEntity, object>>>(z => z = p => p.Id2 == "Some string")))

I get this error:我收到此错误:

Severity Code Description Project File Line Suppression State Error CS1662 Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type严重性代码说明项目文件行抑制状态错误 CS1662 无法将 lambda 表达式转换为预期的委托类型,因为块中的某些返回类型不能隐式转换为委托返回类型

Severity Code Description Project File Line Suppression State Error CS0029 Cannot implicitly convert type 'System.Linq.Expressions.Expression>' to 'bool'严重性代码描述项目文件行抑制状态错误 CS0029 无法将类型“System.Linq.Expressions.Expression>”隐式转换为“bool”

EDIT2编辑2

Signature of the method to mock:模拟方法的签名:

Task<MyEntity> GetByIdAsync(string id, params Expression<Func<MyEntity, object>>[] @params);

I found solution.我找到了解决方案。 You dont need to mock Expression<Func>> , you can simply pass func to Moq like this:您不需要模拟Expression<Func>> ,您可以像这样简单地将 func 传递给Moq

_repositoryMock.Setup(x =>
    x.GetByIdAsync(
        It.Is<string>(y => y == input.Id1),
        z => z.Id2 == "Some id"))
.ReturnsAsync(entity);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM