When to use a Mocking Framework?

六月ゝ 毕业季﹏ 提交于 2019-11-30 15:14:04

问题


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");
    }
}

回答1:


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."

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.




回答2:


There are some rules I use writing unit-tests.

  1. If my System Under Test (SUT) or Object Under Test has dependencies then I mock them all.
  2. If I test a method that returns result then I check result only. If dependencies are passed as parameters of the method they should be mocked. (see 1)
  3. If I test 'void' method then verifying mocks is the best option for testing.

There is an old one article by Martin Fowler Mocks Aren't Stubs.

In first test you use Mock and in the second one you use Stub.

Also I see some design issues that lead to your question.

If it is allowed to remove AkaName from AkaNames collection then it is OK to use stub and check state of the person. If you add specific method void RemoveAkaName(string name) into Person class then mocks should be used in order to verify its invocation. And logic of RemoveAkaName should be tested as part of Person class testing.

I would use stub for product and mock for repository for you code.




回答3:


The mocking framework is used to remove the dependency, so the unit test will focus on the "Unit" to be tested. In your case, the person looks like a simple entity class, there is no need to use Mocking for it.




回答4:


Mocking has many benefits especially in agile programming where many quick release cycles means that sytem strucutre and real data might be incomplete. In such cases you can mock a repository to mimic production code in order to continue work on ui, or services. This is usually complemented with an IoC mechanism like Ninject to simplify the switch to the real repositories. The two examples you give are equal and without any other context I would say it's a matter of choice between them. The fluent api in moq might be easier to read as its kind of self documenting. That's my opinion though ;)




回答5:


Mock is used to test object that cannot function in isolation. suppose function A is dependent on function B, to perform unit testing on function A we even end up testing function B.By using mock you can simulate the functionality of function B and testing can be focussed only on function A.




回答6:


A mocking framework is useful for simulating the integration points in the code under test. I would argue that your concrete example is not a good candidate for a mocking framework as you can already inject the dependency (Person) directly into the code. Using a mocking framework actually complicates it in this case.

A much better use case is if you have a repository making a call to a database. It is desirable from a unit test perspective to mock the db call and return predetermined data instead. The key advantages of this is removing dependencies on exiting data, but also performance since the db call will slow the test down.



来源:https://stackoverflow.com/questions/19674363/when-to-use-a-mocking-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!