首页 > 其他 > 详细

单元测试---Mock

时间:2018-07-26 17:38:58      阅读:149      评论:0      收藏:0      [点我收藏+]

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 Baz
26 {
27     public virtual string Name { get; set; }
28 }

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

1 var mock = new Mock<IFoo>();
2 mock.Setup(foo => foo.DoSomething("ping")).Returns(true);
3 
4 mock.Setup(foo => foo.DoSomething(It.IsAny<int>(),It.IsAny<string>())).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<IFoo>();
2 var calls = 0;
3 var callArgs = new List<string>();
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<IFoo>();
2 mock.SetupSequence(f => f.GetCount())
3     .Returns(3)  // will be returned on 1st invocation
4     .Returns(2)  // will be returned on 2nd invocation
5     .Returns(1)  // will be returned on 3rd invocation
6     .Returns(0)  // will be returned on 4th invocation
7     .Throws(new InvalidOperationException()); 

 

单元测试---Mock

原文:https://www.cnblogs.com/yZiii/p/9372810.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!