单元测试---Mock

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

 

posted @ 2018-07-26 16:55  yZi  阅读(303)  评论(0编辑  收藏  举报