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

查看:418
本文介绍了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
            };
        }
    }

这是我的模拟课程,

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

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

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天全站免登陆