Moq - 不可覆盖的成员不能用于设置/验证表达式 [英] Moq - Non-overridable members may not be used in setup / verification expressions

查看:30
本文介绍了Moq - 不可覆盖的成员不能用于设置/验证表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Moq 的新手.我正在模拟 PagingOptions 类.下面是这个类的样子:

I'm new to Moq. I'm mocking a PagingOptions class. Here is how the class looks like:

public class PagingOptions
    {
        [Range(1, 99999, ErrorMessage = "Offset must be greater than 0.")]
        public int? Offset { get; set; }

        [Range(1, 100, ErrorMessage = "Limit must be greater than 0 and less than 100.")]
        public int? Limit { get; set; }

        public PagingOptions Replace(PagingOptions newer)
        {
            return new PagingOptions
            {
                Offset = newer.Offset ?? Offset,
                Limit = newer.Limit ?? Limit
            };
        }
    }

这是我的课程模拟版本,

Here is my mock version of the class,

var mockPagingOptions = new Mock<PagingOptions>();
            mockPagingOptions.Setup(po => po.Limit).Returns(25);
            mockPagingOptions.Setup(po => po.Offset).Returns(0);

在设置属性值时出现以下错误.我是不是做错了什么.看起来我不能起订具体课程?只能模拟接口吗?请协助.

I get the below error when setting up the property values. Am I making something wrong. Looks like I cannot Moq concrete class? Only Interfaces can be Mocked? Please assist.

谢谢,阿卜杜勒

推荐答案

Moq 创建模拟类型的实现.如果类型是一个接口,它会创建一个实现该接口的类.如果类型是一个类,它会创建一个继承类,该继承类的成员调用基类.但是为了做到这一点,它必须覆盖成员.如果一个类具有不能被覆盖的成员(它们不是虚拟的、抽象的),那么 Moq 不能覆盖它们来添加自己的行为.

Moq creates an implementation of the mocked type. If the type is an interface, it creates a class that implements the interface. If the type is a class, it creates an inherited class, and the members of that inherited class call the base class. But in order to do that it has to override the members. If a class has members that can't be overridden (they aren't virtual, abstract) then Moq can't override them to add its own behaviors.

在这种情况下,不需要模拟 PagingOptions 因为它很容易使用真实的.而不是这样:

In this case there's no need to mock PagingOptions because it's easy to use a real one. Instead of this:

var mockPagingOptions = new Mock<PagingOptions>();
mockPagingOptions.Setup(po => po.Limit).Returns(25);
mockPagingOptions.Setup(po => po.Offset).Returns(0);

这样做:

var pagingOptions = new PagingOptions { Limit = 25, Offset = 0 };

我们如何确定是否嘲笑某事?一般来说,如果我们不想在我们的测试中包含具体的运行时实现,我们会模拟一些东西.我们想测试一个类,而不是同时测试两个类.

How do we determine whether or not to mock something? Generally speaking, we mock something if we don't want to include the concrete runtime implementation in our test. We want to test one class not both at the same time.

但在这种情况下,PagingOptions 只是一个保存一些数据的类.嘲笑它真的没有意义.使用真实的东西一样容易.

But in this case PagingOptions is just a class that holds some data. There's really no point in mocking it. It's just as easy to use the real thing.

这篇关于Moq - 不可覆盖的成员不能用于设置/验证表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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