【C#】MoqのQuickstartをやってみる
参考
https://github.com/Moq/moq4/wiki/Quickstart
Methods
まずはこの辺のメソッドを押さえておけばいいのかな。
- Returns
- Throws
- Callback
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; namespace MoqQuickStart { [TestClass] public class Methods { [TestMethod] public void Practice() { var mock = new Mock<IFoo>(); mock.Setup(foo => foo.DoSomething("ping")).Returns(true); var f = mock.Object; Assert.IsFalse(f.DoSomething("pong")); Assert.IsTrue(f.DoSomething("ping")); } [TestMethod] public void Out_argument() { var outString = "ack"; var mock = new Mock<IFoo>(); mock.Setup(foo => foo.TryParse("ping", out outString)).Returns(true); var f = mock.Object; Assert.IsFalse(f.TryParse("pong", out outString)); Assert.IsTrue(f.TryParse("ping", out outString)); } [TestMethod] public void Ref_argument() { var instance = new Bar(); var mock = new Mock<IFoo>(); mock.Setup(foo => foo.Submit(ref instance)).Returns(true); var f = mock.Object; Assert.IsTrue(f.Submit(ref instance)); } [TestMethod] public void Access_invocation_arguments_when_returning_a_value() { var mock = new Mock<IFoo>(); mock.Setup(x => x.DoSomethingStringy(It.IsAny<string>())) .Returns((string s) => s.ToLower()); var f = mock.Object; var actual = f.DoSomethingStringy("HOGE"); Assert.AreEqual("hoge", actual); } [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void Throwing_when_invoked_with_specific_parameters_1() { var mock = new Mock<IFoo>(); mock.Setup(foo => foo.DoSomething("reset")).Throws<InvalidOperationException>(); mock.Object.DoSomething("reset"); Assert.Fail(); } [TestMethod] public void Throwing_when_invoked_with_specific_parameters_2() { var mock = new Mock<IFoo>(); mock.Setup(foo => foo.DoSomething("")).Throws(new ArgumentException("command")); try { mock.Object.DoSomething(""); Assert.Fail(); } catch (ArgumentException ex) { Assert.AreEqual("command",ex.Message); } } [TestMethod] public void Lazy_evaluating_return_value() { var count = 1; var mock = new Mock<IFoo>(); mock.Setup(foo => foo.GetCount()).Returns(() => count); var actual = mock.Object.GetCount(); Assert.AreEqual(1, actual); } [TestMethod] public void Returning_different_values_on_each_invocation() { var mock = new Mock<IFoo>(); var calls = 0; mock.Setup(foo => foo.GetCount()) .Returns(() => calls) .Callback(() => calls++); Console.WriteLine(mock.Object.GetCount()); Assert.AreEqual(1, calls); Console.WriteLine(mock.Object.GetCount()); Assert.AreEqual(2, calls); } } }