本篇体验Moq的一些基本用法。首先通过NuGet安装Moq。包括:
模拟方法的返回值
public class HelperClass{public virtual Boolean IsEnabled(){throw new Exception();}}[TestClass]public class UnitTest1{[TestMethod]public void TestMethod1(){var mock = new Mock<HelperClass>();
mock.Setup(x => x.IsEnabled()).Returns(true);
Assert.AreEqual(mock.Object.IsEnabled(),true);
}}
● Moq模拟的方法一般是virtual虚方法,接口方法
● mock.Object是指HelperClass的实例
模拟方法后执行回调函数
[TestClass]public class UnitTest1{[TestMethod]public void TestMethod1(){string temp = "";
var mock = new Mock<HelperClass>();
mock.Setup(x => x.IsEnabled()).Returns(true).Callback(() => { temp = "success"; });Assert.AreEqual(mock.Object.IsEnabled(),true);
if (temp == "success"){//TODO
}}}
● 执行Return方法后,执行Callback回调方法,接收的参数类型是委托
模拟方法依次返回多个值
[TestClass]public class UnitTest1{[TestMethod]public void TestMethod1(){var mock = new Mock<HelperClass>();
mock.SetupSequence(x => x.IsEnabled()).Returns(true)
.Returns(false);
Assert.AreEqual(mock.Object.IsEnabled(),true);
Assert.AreEqual(mock.Object.IsEnabled(), false);
}}
● SetupSequence方法可以为方法返回多个值
如果把以下2句:
Assert.AreEqual(mock.Object.IsEnabled(),true);
Assert.AreEqual(mock.Object.IsEnabled(), false);
颠倒一下顺序,变成:
Assert.AreEqual(mock.Object.IsEnabled(), false);
Assert.AreEqual(mock.Object.IsEnabled(),true);
结果,测试不通过。因为SutupSequence返回方法返回值的时候是有顺序的。
模拟第二次调用方法返回异常
[TestClass]public class UnitTest1{[TestMethod]public void TestMethod1(){var mock = new Mock<HelperClass>();
mock.SetupSequence(x => x.IsEnabled()).Returns(true)
.Throws(new Exception());
Assert.AreEqual(mock.Object.IsEnabled(),true);
Assert.AreEqual(mock.Object.IsEnabled(), true);
}}
● 通过Throws方法,在第二次调用IsEnable()方法时抛出异常。
直接返回被模拟方法的原始返回值
public class HelperClass{public virtual Boolean IsEnabled(){throw new Exception();}}[TestClass]public class UnitTest1{[TestMethod]public void TestMethod1(){var mock = new Mock<HelperClass>();
mock.CallBase = true;
mock.SetupSequence(x => x.IsEnabled()).CallBase();Assert.AreEqual(mock.Object.IsEnabled(), true);
}}
在被模拟的HelperClass类中,IsEnabled方法内部抛出异常。当把Moq实例的CallBase属性设置为true,并调用CallBase方法,可在测试方法中直接返回被模拟类中方法的原始返回值。
模拟泛型类
public class HelperClass<T> where T : class{public virtual Boolean IsEnabled(){throw new Exception();}}public class Sample{}[TestClass]public class UnitTest1{[TestMethod]public void TestMethod1(){var mock = new Mock<HelperClass<Sample>>();
mock.SetupSequence(x => x.IsEnabled()).Returns(true);
Assert.AreEqual(mock.Object.IsEnabled(), true);
}}