何时使用模拟框架? [英] When to use a Mocking Framework?

查看:84
本文介绍了何时使用模拟框架?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在为单元测试使用模拟框架(Moq),并且想知道何时应该使用模拟框架?

So I am playing around with mocking frameworks (Moq) for my unit tests, and was wondering when you should use a mocking framework?

以下两个测试之间的优缺点是什么?

What is the benefit/disadvantage between the following two tests:

public class Tests
{
    [Fact]
    public void TestWithMock()
    {
        // Arrange
        var repo = new Mock<IRepository>();

        var p = new Mock<Person>();
        p.Setup(x => x.Id).Returns(1);
        p.Setup(x => x.Name).Returns("Joe Blow");
        p.Setup(x => x.AkaNames).Returns(new List<string> { "Joey", "Mugs" });
        p.Setup(x => x.AkaNames.Remove(It.IsAny<string>()));

        // Act
        var service = new Service(repo.Object);
        service.RemoveAkaName(p.Object, "Mugs");

        // Assert
        p.Verify(x => x.AkaNames.Remove("Mugs"), Times.Once());
    }

    [Fact]
    public void TestWithoutMock()
    {
        // Arrange
        var repo = new Mock<IRepository>();

        var p = new Person { Id = 1, Name = "Joe Blow", AkaNames = new List<string> { "Joey", "Mugs" } };

        // Act
        var service = new Service(repo.Object);
        service.RemoveAkaName(p, "Mugs");

        // Assert
        Assert.True(p.AkaNames.Count == 1);
        Assert.True(p.AkaNames[0] == "Joey");
    }
}

推荐答案

使用模拟对象真正创建单元测试-一种假定所有依赖项都能正常运行并且所有您想执行的测试知道SUT(被测系统-一种表达您正在测试的类的好方法)是否可以正常工作.

Use mock objects to truly create a unit test--a test where all dependencies are assumed to function correctly and all you want to know is if the SUT (system under test--a fancy way of saying the class you're testing) works.

模拟对象有助于正确地保证"您的依赖项功能,因为您创建了这些依赖项的模拟版本,这些版本会产生您配置的结果.问题就变成了,当其他所有东西都在工作"时,您正在测试的一个类是否表现出应有的表现.

The mock objects help to "guarantee" your dependencies function correctly because you create mock versions of those dependencies that produce results you configure. The question then becomes if the one class you're testing behaves as it should when everything else is "working."

当您测试依赖关系较慢的对象(例如数据库或Web服务)时,模拟对象尤为重要.如果您真的要访问数据库或进行真正的Web服务调用,那么您的测试将花费更多的时间来运行.只需几秒钟,就可以忍受,但是当您在连续集成服务器,这加起来非常快,并削弱了您的自动化能力.

Mock objects are particularly critical when you are testing an object with a slow dependency--like a database or a web service. If you were to really hit the database or make the real web service call, your test will take a lot more time to run. That's tolerable when it's only a few extra seconds, but when you have hundreds of tests running in a continuous integration server, that adds up really fast and cripples your automation.

这正是使模拟对象重要的真正原因-减少了构建测试部署周期的时间.确保测试快速运行对于有效的软件开发至关重要.

This is what really makes mock objects important--reducing the build-test-deploy cycle time. Making sure your tests run fast is critical to efficient software development.

这篇关于何时使用模拟框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆