使用 Moq 测试.NET Core 应用
第一篇文章, 关于Mock的概念介绍: https://www.cnblogs.com/cgzl/p/9294431.html
第二篇文章, 关于方法Mock的介绍: https://www.cnblogs.com/cgzl/p/9300356.html
第三篇文章, 关于属性Mock的介绍: https://www.cnblogs.com/cgzl/p/9304567.html
第四篇文章, 关于行为Mock的介绍: https://www.cnblogs.com/cgzl/p/9306728.html
本文介绍使用Moq其它一些功能.
使用的代码: https://github.com/solenovex/Moq4-Tutorial-Code 里面的 05 Before 部分.
https://segmentfault.com/a/1190000017569492 .NET Core单元测试之搞死开发的覆盖率统计
__________________________________________________________________________________
2 3 使用 Moq 测试.NET Core 应用 -- Mock 属性
[Fact]
public void ApproveYoungCheapPlayerTransfer()
{
//递归Mock
Mock<IPhysicalExamination> mockExamination = new Mock<IPhysicalExamination>();
//使用嵌套 子
Mock<IMedicalRoomStatus> medicalRoomStatus = new Mock<IMedicalRoomStatus>();
medicalRoomStatus.Setup(x => x.IsAvailable).Returns("PASS"); //.Returns(true);
//使用嵌套 父
Mock<IMedicalRoom> medicalRoom = new Mock<IMedicalRoom>();
medicalRoom.Setup(x => x.Status).Returns(medicalRoomStatus.Object);
//使用嵌套 父父
mockExamination.Setup(x => x.MedicalRoom).Returns(medicalRoom.Object);
//mockExamination.Setup(x =>
// x.IsHealthy(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>())).Returns(true);
mockExamination.Setup(x => x.IsMedicalRoomAvailable).Returns(true);
mockExamination.Setup(x =>
x.IsHealthy(
It.Is<int>(age => age < 30),
It.IsIn<int>(80, 85, 90),
It.IsInRange<int>(75, 99, Range.Inclusive)))
.Returns(true);
var approval = new TransferApproval(mockExamination.Object);
var emreTransfer = new TransferApplication
{
PlayerName = "Emre Can",
PlayerAge = 24,
TransferFee = 0,
AnnualSalary = 4.52m,
ContractYears = 4,
IsSuperStar = false,
PlayerStrength = 80,
PlayerSpeed = 75,
};
var result = approval.Evaluate(emreTransfer);
Assert.Equal(TransferResult.Approved, result);
}
[Fact]
public void ApproveYoungCheapPlayerTransfer01()
{
//递归Mock可以为Mock对象设定默认值
Mock<IPhysicalExamination> mockExamination = new Mock<IPhysicalExamination>() {
DefaultValue= DefaultValue.Mock
};
//使用嵌套
mockExamination.Setup(x => x.MedicalRoom.Status.IsAvailable).Returns("PASS");//.Returns(true);
//mockExamination.Setup(x =>
// x.IsHealthy(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>())).Returns(true);
mockExamination.Setup(x => x.IsMedicalRoomAvailable).Returns(true);
mockExamination.Setup(x =>
x.IsHealthy(
It.Is<int>(age => age < 30),
It.IsIn<int>(80, 85, 90),
It.IsInRange<int>(75, 99, Range.Inclusive)))
.Returns(true);
var approval = new TransferApproval(mockExamination.Object);
var emreTransfer = new TransferApplication
{
PlayerName = "Emre Can",
PlayerAge = 24,
TransferFee = 0,
AnnualSalary = 4.52m,
ContractYears = 4,
IsSuperStar = false,
PlayerStrength = 80,
PlayerSpeed = 75,
};
var result = approval.Evaluate(emreTransfer);
Assert.Equal(TransferResult.Approved, result);
}
[Fact]
public void PhysicalGradeShouldPassWhenTransferringSuperStar()
{
var mockExamination = new Mock<IPhysicalExamination>
{
DefaultValue = DefaultValue.Mock
};
mockExamination.SetupAllProperties();
// 开始追踪PhysicalGrade属性
mockExamination.SetupProperty(x => x.PhysicalGrade, PhysicalGrade.Failed);
mockExamination.Setup(x => x.IsHealthy(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>())).Returns(true);
var approval = new TransferApproval(mockExamination.Object);
var cr7Transfer = new TransferApplication
{
PlayerName = "Cristiano Ronaldo",
PlayerAge = 33,
TransferFee = 112m,
AnnualSalary = 30m,
ContractYears = 4,
IsSuperStar = true,
PlayerStrength = 90,
PlayerSpeed = 90
};
var result = approval.Evaluate(cr7Transfer);
Assert.Equal(PhysicalGrade.Passed, mockExamination.Object.PhysicalGrade);
}
[Fact]
public void ReferredToBossWhenTransferringSuperStar()
{
var mockExamination = new Mock<IPhysicalExamination>(MockBehavior.Strict);
mockExamination.SetupAllProperties();
mockExamination.Setup(x => x.MediacalRoom.Status.IsAvailable).Returns("Available");
//mockExamination.SetupProperty(x => x.PhysicalGrade, PhysicalGrade.Passed);
//追踪属性配置默认值 追踪所有属性 mockExamination.SetupAllProperties() 必须放在第一行;
//mockExamination.SetupProperty(x => x.PhysicalGrade, PhysicalGrade.Failed);
mockExamination.Setup(x => x.IsHealthy(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>())).Returns(true);
var approval = new TransferApproval(mockExamination.Object);
var cr7Transfer = new TransferApplication
{
PlayerName = "Cristiano Ronaldo",
PlayerAge = 33,
TransferFee = 112m,
AnnualSalary = 30m,
ContractYears = 4,
IsSuperStar = true,
PlayerStrength = 90,
PlayerSpeed = 90
};
var result = approval.Evaluate(cr7Transfer);
// Assert.Equal(TransferResult.ReferredToBoss, result);
Assert.Equal(PhysicalGrade.Passed, mockExamination.Object.PhysicalGrade);
}
4 使用Moq 测试.NET Core 应用 -- Mock 行为
[Fact]
public void ShouldPhysicalExamineWhenTransferringSuperStar()
{
var mockExamination = new Mock<IPhysicalExamination>();
mockExamination.Setup(x => x.MediacalRoom.Status.IsAvailable).Returns("Available");
mockExamination.SetupProperty(x => x.PhysicalGrade, PhysicalGrade.Passed);
mockExamination.Setup(x => x.IsHealthy(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>())).Returns(true);
var approval = new TransferApproval(mockExamination.Object);
var cr7Transfer = new TransferApplication
{
PlayerName = "Cristiano Ronaldo",
PlayerAge = 33,
TransferFee = 112m,
AnnualSalary = 30m,
ContractYears = 4,
IsSuperStar = true,
PlayerStrength = 90,
PlayerSpeed = 90
};
var result = approval.Evaluate(cr7Transfer);
result = approval.Evaluate(cr7Transfer);
// Assert.Equal(TransferResult.ReferredToBoss, result);
// mockExamination.Verify(x => x.IsHealthy(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>())); //判断指定的事件是否执行
// mockExamination.Verify(x => x.IsHealthy(33, 95, 88), "Arguments not match !!!!"); //判断指定的事件是否执行
//mockExamination.Verify(x => x.IsHealthy(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>()), Times.Exactly(2)); //判断指定的事件执行次数
//mockExamination.VerifyGet(x => x.MediacalRoom.Status.IsAvailable);
mockExamination.VerifySet(x => x.PhysicalGrade = PhysicalGrade.Passed);//判断PhysicalGrade属性已经被赋值了 PhysicalGrade.Passed
}
5. 使用 Moq 测试.NET Core 应用 -- 其它
[Fact]
public void PostponedWhenTransferringChildPlayer()
{
//mockExamination.Setup(x => x.IsHealthy(It.Is<int>(age => age < 16), It.IsAny<int>(), It.IsAny<int>()))
// .Throws<Exception>();
mockExamination.Setup(x => x.IsHealthy(It.Is<int>(age => age < 16), It.IsAny<int>(), It.IsAny<int>()))
.Throws(new Exception("The player is still a child"));
var childTransfer = new TransferApplication
{
PlayerName = "Some Child Player",
PlayerAge = 13,
TransferFee = 0,
AnnualSalary = 0.01m,
ContractYears = 3,
IsSuperStar = false,
PlayerStrength = 40,
PlayerSpeed = 50
};
var result = approval.Evaluate(childTransfer);
Assert.Equal(TransferResult.Postponed, result);
}
[Fact]
public void ShouldPlayerHealthCheckedWhenTransferringSuperStar()
{
//事件是否调用
mockExamination.DefaultValue = DefaultValue.Mock;
mockExamination.Setup(x => x.MediacalRoom.Status.IsAvailable).Returns("Avaliable");
mockExamination.SetupProperty(x => x.PhysicalGrade, PhysicalGrade.Passed);
mockExamination.Setup(x => x.IsHealthy(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>()))
.Returns(true)
.Raises(x => x.HealthChecked += null, EventArgs.Empty);
//mockExamination.Setup(x => x.IsHealthy(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>()))
// .Returns(true)
// .Raises(x => x.HealthChecked += null, EventArgs.Empty);
var cr7Transfer = new TransferApplication
{
PlayerName = "Cristiano Ronaldo",
PlayerAge = 33,
TransferFee = 112m,
AnnualSalary = 30m,
ContractYears = 4,
IsSuperStar = true,
PlayerStrength = 90,
PlayerSpeed = 90
};
var result = approval.Evaluate(cr7Transfer);
//mockExamination.Raise(x => x.HealthChecked+=null, EventArgs.Empty);
Assert.True(approval.PlayerHealthChecked);
}
[Fact]
public void ShouldPostponedWhenNotInTransferPeriod()
{
//使用没有实现接口的方法, 注意这个方法必须是 virtual
mockTransferPolicy.Setup(x => x.IsInTransferPeriod()).Returns(false);
mockTransferPolicy.Protected().Setup<bool>("IsBannedFromTransferring") //Protected() 注意 protected
//.Setup<bool>("IsBannedFromTransferring",ItExpr.IsAny<String>()) //有参数的话, 需要用到ItExpr类.
.Returns(true);
//mockTransferPolicy.Protected()
// .Setup<bool>("IsBannedFromTransferring")
// // .Setup<bool>("IsBannedFromTransferring", ItExpr.IsAny<string>())
// .Returns(true);
var cr7Transfer = new TransferApplication
{
PlayerName = "Cristiano Ronaldo",
PlayerAge = 33,
TransferFee = 112m,
AnnualSalary = 30m,
ContractYears = 4,
IsSuperStar = true,
PlayerStrength = 90,
PlayerSpeed = 90
};
var result = approval.Evaluate(cr7Transfer);
Assert.Equal(TransferResult.Postponed, result);
}
[Fact]
public void LinqToMocks()
{
//Linq to Mocks 一次性为测试Mock对象配置返回值
var mockExamination = Mock.Of<IPhysicalExamination>
(
me => me.MediacalRoom.Status.IsAvailable == "Available" &&
me.PhysicalGrade == PhysicalGrade.Passed &&
me.IsHealthy(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<int>()) == true
);
var mockTransferPolicy = Mock.Of<TransferPolicyEvaluator>
(
mt => mt.IsInTransferPeriod() == false
);
approval = new TransferApproval(mockExamination, mockTransferPolicy);
var cr7Transfer = new TransferApplication
{
PlayerName = "Cristiano Ronaldo",
PlayerAge = 33,
TransferFee = 112m,
AnnualSalary = 30m,
ContractYears = 4,
IsSuperStar = true,
PlayerStrength = 90,
PlayerSpeed = 90
};
var result = approval.Evaluate(cr7Transfer);
Assert.Equal(TransferResult.Postponed, result);
}
使用 Moq 测试.NET Core 应用的更多相关文章
- 使用 Moq 测试.NET Core 应用 - Why Moq?
什么是Mock 当对代码进行测试的时候, 我们经常需要用到一些模拟(mock)技术. 绿色的是需要被测试的类, 黄色是它的依赖项, 灰色的无关的类 在一个项目里, 我们经常需要把某一部分程序独立出来以 ...
- 使用 Moq 测试.NET Core 应用 -- Mock 方法
第一篇文章, 关于Mock的概念介绍: https://www.cnblogs.com/cgzl/p/9294431.html 本文介绍使用Moq来Mock方法. 使用的代码: https://git ...
- 使用 Moq 测试.NET Core 应用 -- Mock 属性
第一篇文章, 关于Mock的概念介绍: https://www.cnblogs.com/cgzl/p/9294431.html 第二篇文章, 关于方法Mock的介绍: https://www.cnbl ...
- 使用 Moq 测试.NET Core 应用 -- Mock 行为
第一篇文章, 关于Mock的概念介绍: https://www.cnblogs.com/cgzl/p/9294431.html 第二篇文章, 关于方法Mock的介绍: https://www.cnbl ...
- 使用 Moq 测试.NET Core 应用 -- 其它
第一篇文章, 关于Mock的概念介绍: https://www.cnblogs.com/cgzl/p/9294431.html 第二篇文章, 关于方法Mock的介绍: https://www.cnbl ...
- Moq 测试 属性,常用方法
RhinoMock入门(7)——Do,With和Record-playback 摘要: (一)Do(delegate)有时候在测试过程中只返回一个静态的值是不够的,在这种情况下,Do()方法可以用来在 ...
- Moq 在.net Core 单元测试中的使用
Moq,主要用来伪造接口的实现类,实现方法,属性 moq The most popular and friendly mocking framework for .NET What? Moq (pro ...
- solr安装部署、solr测试创建core、用solrj 访问solr(索引和搜索)
一.安装solr4.8: 1.把apache-solr-4.8.1\example\webapps下的solr.war文件拷贝到Tomcat下的Tomcat7.0\webapps目录下,tomcat启 ...
- 利用BenchmarkDotNet 测试 .Net Core API 同步和异步方法性能
事由: 这两天mentor给我布置了个任务让我用BenchmarkDotNet工具去测试一下同一个API 用同步和异步方法写性能上有什么差别. 顺带提一下: 啊啊啊啊 等我仔细看文档的时候文档 发现它 ...
随机推荐
- vray学习笔记(2)vray工作流程
在bilibili上面搜索到了一个vray的教程,虽然是英语的,细节方面可能听不太懂,但可以了解整个工作流程,工作流程太重要了,先看下视频的目录: 第1节到第9节都是建模的内容. 第10节和第13节是 ...
- can通信实验
源码讲解 1.硬件连接 需要两个开发板 2.初始化函数讲解 针对F103的 3.发送函数讲解 4.接收函数讲解 5.main函数讲解
- 【IMOOC学习笔记】多种多样的App主界面Tab实现方法(二)
Fragment实现Tab 首先把activity_main.xml 文件中的ViewPager标签改成Fragment标签 <FrameLayout android:id="@+id ...
- [译]Javasctipt中的substring
本文翻译youtube上的up主kudvenkat的javascript tutorial播放单 源地址在此: https://www.youtube.com/watch?v=PMsVM7rjupU& ...
- Web开发秘方(WEB DEVELOPMENT RECIPES)[47.5MB] PDF扫描版
不借助插件怎样在移动设备上实现动画效果?怎样快速搭建HTML电子邮箱?怎样制作跨PC和移动设备显示的应用界面?怎样利用最新的JavaScript框架提高应用的响应速度?怎样有效利用CoffeeScri ...
- 【Arcgis for android】保存地图截图到sd卡
关键词:arcgis for android ,截图,bitmap,sd卡 参考文章:http://blog.csdn.net/wozaifeiyang0/article/details/767972 ...
- txt中把换行替换为空格
把合适改为html后打开,换行都没了,然后复制到另一个txt即可
- C#修饰符讲解大全
1.修饰符是什么? 修饰符是用于限定类型以及类型成员的声明的一种符号.[百度百科] 2.修饰符分类 13种修饰符,按功能可分为三类:访问修饰符,类修饰符和成员修饰符.[百度百科] 作 用:限定类型以及 ...
- java java启动方式
java启动方式 两种方案: 1.守护进程方式启动: java –jar命令: 例如:C:\eclise\work\test.jar C:\eclise\work\test.java 打开dos:输 ...
- Django会话,用户和注册之cookie
HTTP状态和TCP不一样,HTTP是无状态的,也就是这一次请求和下一次请求之间没有任何状态保持,我们无法根据请求例如IP来识别是否在同一人的连续性请求.就像我们在访问网站的时候,输入了用户名和密码, ...