测试:

public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
Mock<TestClass> moc = new Mock<TestClass>();
moc.Setup(x => x.GetItem(It.IsAny<int>())).Returns("123");
moc.Setup(x => x.name).Returns("wgscd");
TestClass t =moc.Object;
Assert.AreEqual("123", t.GetItem(222));
Assert.AreEqual("wgscd", t.name); }
} public class TestClass
{
public string GetItem(int i) {
return "";
}
public string name { get;set; } }

  

上面代码会错误出现:

Moq - Non-overridable members may not be used in setup / verification expressions

修改后OK:

public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
Mock<TestClass> moc = new Mock<TestClass>();
moc.Setup(x => x.GetItem(It.IsAny<int>())).Returns("123");
moc.Setup(x => x.name).Returns("wgscd");
TestClass t =moc.Object;
Assert.AreEqual("123", t.GetItem(222));
Assert.AreEqual("wgscd", t.name); }
} public class TestClass
{
public virtual string GetItem(int i) {
return "";
}
public virtual string name { get;set; } }

  

原因是:moc 的对象的成员或字段必须可以 override 的。

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.

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);

Do this:

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.

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.

另外有个回答的还提到测试私有字段的方法(就是通过反射设置私有字段值):

n case you reached this question based on the original title Non-overridable members may not be used in setup / verification expressions and none of the other answers have helped you may want to see if reflection can satisfy your test needs.

Suppose you have a class Foo with a property defined as public int I { get; private set; }

If you try the various methods in the answers here few of them will work for this scenario. However you can use .net reflection to setup a value of an instance variable and still keep fairly good refactoring support in the code.

Here is a snippet that sets a property with a private setter:

var foo = new Foo();
var I = foo.GetType().GetProperty(nameof(Foo.I), BindFlags.Public | BindingFlag.Instance);
I.SetValue(foo, 8675309);

C# Moq - Non-overridable members may not be used in setup / verification expressions的更多相关文章

  1. 开源项目Foq简介

        Foq是一个轻量级-线程安全的mocking类库.使用它来mock抽象类与接口这是我们通常的做法.Foq的名字来自Moq,如果你使用过Moq的话,自然后联想到它能做什么.Foq主要是为了F#的 ...

  2. C#7的9个新语法

    一.out变量 在c#7之前我们得这样 在c#7中我们可以这样 当然你还可以使用"var" 这算一个小更新,其实这个问题存在很久了,应该也很好解决,不知为何到c#7才开始引入,不管 ...

  3. mshadow的原理--MXNet

    mshadow的原理--MXNet 这文章主要解释了表达式模板的工作原理(也是mshadow的主要原理),文章的前半部分是翻译自exp-template/README.md.我们会解释它为什么会影响编 ...

  4. C#7

    C#7 阅读目录 out变量 元组(Tuples) 模式匹配(Pattern matching) 本地引用和返回(Ref locals and returns) 本地函数(Local function ...

  5. Cyber Security - Palo Alto Firewall Interface Types

    Multiple options to integrate the Palo Alto Firewall into your: Network Layer 2 interfaces and VLAN ...

  6. MShadow中的表达式模板

    表达式模板是Eigen.GSL和boost.uBLAS等高性能C++矩阵库的核心技术.本文基于MXNet给出的教程文档来阐述MXNet所依赖的高性能矩阵库MShadow背后的原理. 编写高效的机器学习 ...

  7. c#单元测试:使用Moq框架Mock对象

    在.net中有几种mock框架可供选择,比如NMock,PhinoMocks,FakeItEasy和Moq.尽管Moq相对较新,但是它非常易用.不需要像传统的Record/Replay.并且使用Moq ...

  8. C# Moq

    Moq 1 My Cases 1.1 简单入门 2 Reference 2.1 Methods 2.2 Matching Arguments 2.3 Properties 2.4 Events 2.5 ...

  9. AutoMapper:Unmapped members were found. Review the types and members below. Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type

    异常处理汇总-后端系列 http://www.cnblogs.com/dunitian/p/4523006.html 应用场景:ViewModel==>Mode映射的时候出错 AutoMappe ...

  10. Moq基础

    一.概念 Moq是利用诸如Linq表达式树和Lambda表达式等·NET 3.5的特性,为·NET设计和开发的Mocking库.Mock字面意思即模拟,模拟对象的行为已达到欺骗目标(待测试对象)的效果 ...

随机推荐

  1. centos7LDAP服务搭建

    ladp服务搭建 用户名:cn=admin,dc=test,dc=com 密码:123456 1)软件安装yum install openldap openldap-clients openldap- ...

  2. Unity6 URP17使用初探

    1.简介 随着Unity6的发布,URP17也已经可以上手使用,相对旧的版本改动较大的是加入了 RenderGraph.STP.Foveated rendering.GPU Resident Draw ...

  3. Ubuntu 无法播放MP4

    今天用ubuntu打开mp4发现无法播放,然后我以为文件损坏了,就传到手机上面,发现还是可以播放的,然后就查了一下相关资料,发现有人让我安装这个 sudo snap install ffmpeg 安装 ...

  4. 自定义 MySQL Shell 提示符

    MySQL Shell 中的提示符的样式和格式可以根据使用者的需求进行定制.我们可以配置提示符以显示有关数据库连接和使用的模式的不同或简化信息.本文将展示如何添加视觉提示,让您知道何时连接到生产数据库 ...

  5. Gunicorn 部署 Flask-Apscheduler 重复执行问题

    目录 踩坑一:TimeZone offset does not match system offset 踩坑二:Flask-Apscheduler 多进程环境重复运行 踩坑三:集群环境下,Flask- ...

  6. DB2 pureXML 动态编程组合拳:iBatis+BeanUtils+JiBX

    黄耀华, 软件工程师, IBM 李玉明 (ymli@cn.ibm.com), 软件工程师, Systems Documentation, Inc. (SDI) 袁飞 (feiyuan@cn.ibm.c ...

  7. Python数据存储之shelve和dbm

    一.shelve 和 dbm 的介绍 shelve 和 dbm 都是 python 自带的数据库管理模块,可以用于持久化存储和检索 python 中的对象. 虽然这两个模块的本质都是建立 key-va ...

  8. YAML语法基础

    YAML 的意思其实是:"Yet Another Markup Language"(仍是一种标记语言). YAML 的语法和其他高级语言类似,并且可以简单表达清单.散列表,标量等数 ...

  9. 从Hbase shell理解列式存储

    列存储和行存储在理解上的差别挺大,特别是在非常数据行存储之后. 在行存储中,每张表的结构是固定的,某一列可以没有值但是这一列是必须在的.那么可以理解行存储的数据是结构化的. 但是列存储确有每行的数据却 ...

  10. 关于xml文件解析时'&'不能被解析的问题

    Bug情况:在解析xml文件的时候,&字符解析错误 解决方式:将符号进行转义