测试:

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. 题解:NOIP2023 天天爱打卡

    NOIP2023 天天爱打卡 - luogu 算法一 upd :2024/10/31. 记 \(f[i]\) 表示第 \(i\) 天休息, \(1\sim i\) 天能获得的最大能量. 考虑如何从 \ ...

  2. Anaconda安装流程

    参考这篇博客,自己做一个记录而已anaconda安装 https://blog.csdn.net/Q_fairy/article/details/129158178

  3. delphi 图形图像处理 Image32

    delpher 越来越少了,但不能掩盖它的优秀,很外前看到了 Image32,但发现用它的人很少,这段时间整理了它的资料,重新组合了一个DEMO,也可以说是个小工具,分享出来. Image32 关于I ...

  4. 国产数据库oceanBbase,达梦,金仓与mysql数据库的性能对比 一、比对方法和结果

    最近调研了三款国产化数据库与mysql做对比,调研主要性能指标是大数据写入速度.大数据读取速度以及是否支持分表. 一.测试结果 测试结果与预期的差别很大     1.先说oceanBase社区版这款数 ...

  5. 升级Linux内核版本

    ```shell# 查看内核版本,jw版本ceph默认format=2, 2.x 及之前的的内核版本需手动调整format=1# 4.x之前要关闭object-map fast-diff deep-f ...

  6. 【集成-Jedis】SpringBoot集成Jedis

    将jedis的依赖放进Maven <dependency> <groupId>redis.clients</groupId> <artifactId>j ...

  7. canvas(一)描边与填充

    1.画布大小 canvas默认的大小是 300*150,通过操作width/height属性可以设置画布的大小,属性值只能是具体是像素值,而不能是百分比. <body> <div c ...

  8. C#/.NET/.NET Core技术前沿周刊 | 第 16 期(2024年12.01-12.08)

    前言 C#/.NET/.NET Core技术前沿周刊,你的每周技术指南针!记录.追踪C#/.NET/.NET Core领域.生态的每周最新.最实用.最有价值的技术文章.社区动态.优质项目和学习资源等. ...

  9. 【Rive】波动文字

    1 前言 ​ 本文将使用文本修改器(Text Modifiers)做文字动画,实现文字波动效果. ​ 按以下步骤可以创建一个 Modifier Group 和 Range. ​ 部分参数的释义如下. ...

  10. mongo docker compose

    49dSsULIAv6NiP8hdqqbapRTHVx9BRYU4VVakN9A4FJWV0KufqEm/UoTUvn9Z4eg FRP7iHXF6Qiou5MK2Ak76zRBU7MOIVCl0DI ...