模拟对象测试技术Mock

因为目前项目时间比较紧(一个月的开发周期),并且,工作流的测试步骤也比较多,所以,我决定采用一种模拟对象测试技术:Mock。Mock可以为接口生成模拟对象,从而在我们写实现代码之前就检查其逻辑和交互行为是否正确。我们选用的Mock框架是Moq 3,基于lambda语法的一款非常简单的Mock框架。

下面使用示例向大家介绍Mock测试框架的好处:

IEmployee.cs

namespace Thoth.FeatureProject {
public interface IEmployee {
int Identifier { get; set; }
string Name { get; set; }
int Age { get; set; }
}
}

ISeat.cs

namespace Thoth.FeatureProject {
public interface ISeat {
IEmployee Get(int identifier);
}
}

MainTest.cs

using Moq;
using NUnit.Framework;
using Thoth.FeatureProject;

namespace Thoth.MoqProject {
[TestFixture]
public class MainTest {
[Test]
public void EmployeeTest() {
var employee = new Mock();
employee.SetupGet(p => p.Identifier).Returns(1);
employee.SetupGet(p => p.Name).Returns(“Justina Chen”);
employee.SetupGet(p => p.Age).Returns(28);
Assert.AreEqual(“Justina Chen”, employee.Object.Name);

        var seat = new Mock();
        seat.Setup(p => p.Get(1)).Returns(employee.Object);
        var seatReturned = seat.Object.Get(1);
        Assert.AreEqual("Justina Chen", seatReturned.Name);

        var seatI = new Mock();
        seatI.Setup(p => p.Get(It.IsAny())).Returns(employee.Object);
        var seatNewReturned = seatI.Object.Get(1);
        Assert.AreEqual("Justina Chen", seatNewReturned.Name);

        var seatII = new Mock();
        seatII.Setup(p => p.Get(It.Is(id => id > 0 && id < 6))).Returns(employee.Object);
        var seatNewConditionReturned = seatII.Object.Get(1);
        Assert.AreEqual("Justina Chen", seatNewConditionReturned.Name);
}
}

}
上面的测试全部通过。

大家注意到了吗,我只写了两个接口,而创建Mock对象之后,我就可以以实例的方式测试对象的行为了,如果不正确,我们这时就可以对接口的设计进行修改。下面是注释:

//创建一个Mock对象(泛型)
var employee = new Mock();

//为此Mock对象的一个属性(这行是针对Identifier)值(SetupGet是为接口的Property设置值,值在Return()方法中)
employee.SetupGet(p => p.Identifier).Returns(1);

//取出Mock对象的值,检查是否正确
Assert.AreEqual(“Justina Chen”, employee.Object.Name);

//为Mock对象的方法设置一个参数及返回对象(Setup针对的是方法),Returns是返回对象,Get(1)中值为1的参数
seat.Setup(p => p.Get(1)).Returns(employee.Object);

//这两行检查我们返回结果是否正确
var seatReturned = seat.Object.Get(1);
Assert.AreEqual(“Justina Chen”, seatReturned.Name);

//这行是指任何int参数都返回此对象
seat.Setup(p => p.Get(It.IsAny())).Returns(employee.Object);

//这里指定了一个筛选条件
seat.Setup(p => p.Get(It.Is(id => id > 0 && id < 6))).Returns(employee.Object);

//那么,下面的测试结果是?
var seatIII = new Mock();
seatIII.Setup(p => p.Get(1)).Returns(employee.Object);
var seatObject = seatIII.Object.Get(0);
Assert.AreEqual(“Justina Chen”, seatObject.Name);

seatObject.Name将报出NullRefenrenceException,因为我们Setup的是1,而希望获取的对象是0,所以,检索为空 :-)

我们项目中目前运用到的Mock技术差不多就是这样了,希望能减轻大家跑流程的步骤 :-D 随着使用的深入,会继续与大家分享。

© 2018 Silent River All Rights Reserved. 本站访客数人次 本站总访问量
Theme by hiero