博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
单元测试---Mock
阅读量:4552 次
发布时间:2019-06-08

本文共 1934 字,大约阅读时间需要 6 分钟。

mock测试就是在中,对于某些不容易构造或者不容易获取的对象,用一个虚拟的对象来创建以便测试的测试方法.

1 using Moq; 2  3 // Assumptions: 4  5 public interface IFoo 6 { 7     Bar Bar { get; set; } 8     string Name { get; set; } 9     int Value { get; set; }10     bool DoSomething(string value);11     bool DoSomething(int number, string value);12     string DoSomethingStringy(string value);13     bool TryParse(string value, out string outputValue);14     bool Submit(ref Bar bar);15     int GetCount();16     bool Add(int value);17 }18 19 public class Bar 20 {21     public virtual Baz Baz { get; set; }22     public virtual bool Submit() { return false; }23 }24 25 public class Baz26 {27     public virtual string Name { get; set; }28 }

上面给了一个类,接下来演示怎么mock这个类,并且模拟某些方法的返回值

1 var mock = new Mock
();2 mock.Setup(foo => foo.DoSomething("ping")).Returns(true);3 4 mock.Setup(foo => foo.DoSomething(It.IsAny
(),It.IsAny
())).Returns(true);

第一行Mock出了一个虚拟对象

第二行说明当调用IFoo的DoSomething(string value)方法,且传入参数"ping"的时候,不论DoSomething里面的代码是什么,都会返回true,即直接跳过DoSomething里面的所有代码

第三行说明当调用IFoo的DoSomething(int num,string value)时,不论传入的num和value值为什么,都返回true

 

能设置方法的返回值,当然也能设置属性的值

1 mock.Setup(foo => foo.Name).Returns("bar");

 

还有一些神奇的操作,我太懒了不想写,放个代码示例方便查看~~

Callbacks

1 var mock = new Mock
();2 var calls = 0;3 var callArgs = new List
();4 5 mock.Setup(foo => foo.DoSomething("ping"))6 .Returns(true)7 .Callback(() => calls++);

Verification

1 mock.Verify(foo => foo.DoSomething("ping"));

miscellaneous

1 var mock = new Mock
();2 mock.SetupSequence(f => f.GetCount())3 .Returns(3) // will be returned on 1st invocation4 .Returns(2) // will be returned on 2nd invocation5 .Returns(1) // will be returned on 3rd invocation6 .Returns(0) // will be returned on 4th invocation7 .Throws(new InvalidOperationException());

 

转载于:https://www.cnblogs.com/yZiii/p/9372810.html

你可能感兴趣的文章
大数加法和乘法(高精度)
查看>>
利用SynchronizationContext.Current在线程间同步上下文
查看>>
单片机reg51.h头文件详解(1)
查看>>
python各种类型转换-int,str,char,float,ord,hex,oct等
查看>>
sublime Text3 快捷键
查看>>
19 年书单
查看>>
规范 : Sql statusEnum
查看>>
jQuery的.live()和.die() 使用介绍
查看>>
mybatis
查看>>
Chord算法(原理)
查看>>
cocos2d-html5
查看>>
不变模式
查看>>
RabbitMQ安装与搭建
查看>>
【转】UITextView检查已输入字符字数
查看>>
延迟初始化
查看>>
字符串格式化和format
查看>>
页面内容添加新的显示或者显示隐藏的内容,滚动条滚动到最低端,显示出新内容...
查看>>
【poj1182】 食物链
查看>>
Oracle学习之start with...connect by子句的用法
查看>>
matlab去云雾
查看>>