Moq
1 My Cases
1.1 簡單入門
2 Reference
2.1 Methods
2.2 Matching Arguments
2.3 Properties
2.4 Events
2.5 Callbacks
2.6 Verification
2.7 Customizing Mock Behavior
2.8 Miscellaneous
2.9 Advanced Features
2.10 LINQ to Mocks
3 FAQ
3.1 static class/method
1 My Cases
1.1 簡單入門
// 假定我有一個 MyFactory 用來創建 MyInterface 實例
// 創建 MyFactory 的 Mock 對象 var mockFactory = new Mock<MyFactory>(); // 創建 MyInterface 的 Mock 實例 var mockInstance = new Mock<MyInterface>(); // 使用 Moq 實現如果調用 MyInstance.DoSomething(bool) 方法無論傳入參數為何值一概拋出 MyException 異常 mockInstance.Setup(c => c.DoSomething(It.IsAny<bool>())) .Throws(new MyException("my exception message")); // 使用 Moq 實現 MyFactory 的 Mock 實例第一次調用 CreateInstance(string) 方法時返回 MyInterface 的 Mock 實例 // 第二次及以后調用則返回真正的 MyInstance 實例 mockFactory.SetupSequence(f => f.CreateInstance(It.IsAny<string>())) .Returns(mockInstance.Object) .Returns(new MyInstance("real object")); client.Factory = mockFactory.Object;
2 Reference
Please refer to Moq Quickstart
Moq is intended to be simple to use, strongly typed (no magic strings!, and therefore full compiler-verified and refactoring-friendly) and minimalistic (while still fully functional!).