带有lambda表达式的最小起订量? [英] Moq with lambda expressions?

查看:85
本文介绍了带有lambda表达式的最小起订量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Moq 4.0.10827(在NuGet上)测试应用程序服务,并且需要查询存储库:

I am trying to test an application service using Moq 4.0.10827 (on NuGet) and need to query a repository:

public class MyService
{
    Repository<MyObject> _Repo;

    public MyObject Get (string SomeConstraint)
    {
        return _Repo
            .GetTheFirstOneOrReturnNull (M => M.Constraint.Equals (
                SomeContraint, StringComparison.InvariantCultureIgnoreCase
            ));  // GetTheFirstOneOrReturnNull takes a Func<MyObject, bool>
    }
}

如何使用Moq复制lambda表达式?我不断收到不支持的表达式"异常.

How do I replicate the lambda expression with Moq? I keep getting the "Unsupported expression" exception.

以下是我已经在做的事情的想法:

Here is an idea of what I'm doing already:

[TestMethod]
public void GetByMyConstraintShouldReturnWithMyObject ()
{
    // Arrange
    const string MyConstraint = "Constraint";
    MyObject Expected = new MyObject { Constraint = MyConstraint };
    Mock<Repository<MyObject>> MockRepo = new Mock<Repository<MyObject>> ();
    MockRepo.Setup (x => x.GetTheFirstOneOrReturnNull (M => M.Constraint.Equals (MyConstraint, StringComparison.InvariantCultureIgnoreCase)))
            .Returns (Expected).Verifable ();
    MyService Service = new MyService (MockRepo.Object);

    // Act
    MyObject Result = Service.Get (MyConstraint);


    // Assert
    Assert.AreSame (Expected, Result);
    MockRepo.Verify ();

}

我已经环顾了其他一些答案,但是我无法真正弄清自己做错了什么(承认是Moq的傻瓜").我得出的结论是,这将是很痛苦的,但是我要进行很多类似的测试,并且希望现在变得牢固,而不是以后淹死.

I've looked around at some of the other answers but I cannot really make out what I am doing incorrectly (admittedly a "noob" with Moq). I have come to the conclusion that this is going to be a pain but I have a lot of tests like this coming up and want to get solid now instead of drowning later.

将lambda表达式封装在一个对象内并传递到存储库中并使其执行查询是唯一的选择吗?我不想只为我的测试环境更改代码,但是我也不想浪费时间尝试按照我的意愿来修改此代码.

Is the only option to encapsulate the lambda expression inside of an object and pass in the repository and have it execute the query? I don't want to change my code just for my testing environment, but I don't want to waste time trying to bend this thing to my will, either.

推荐答案

这不需要太多测试.一个正确的测试将显示委托给FirstOrDefault的代码正在工作,然后所有后续测试都实际上在测试Func约束中的逻辑是否正确,而无需将其传递给Repository即可.

This shouldn't need much testing. One correct test will show the code delegating to FirstOrDefault is working, then all subsequent tests are really testing that the logic in the Func constraint is correct which can be done without passing it into the Repository.

这篇关于带有lambda表达式的最小起订量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆