1. 程式人生 > >單元測試---Mock

單元測試---Mock

一行 構造 ica using ike face turn public ber

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