When to use a Mocking Framework?

11,236

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

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

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

Solution 4

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.

Solution 5

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

Share:
11,236

Related videos on Youtube

Sam
Author by

Sam

.Net Developer with a strong emphasis on client side technologies.

Updated on June 04, 2022

Comments

  • Sam
    Sam almost 2 years

    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");
        }
    }
    
    • crthompson
      crthompson over 10 years
      Mocking allows you to control all the variables that you are NOT testing, so that you only test one piece of code.
    • citykid
      citykid over 10 years
      +1 paqogomez, in other words, mocking allows you to isolate the code under test, so that you only test a particular code piece. the benefit is that a red or green test result indicates which part of the code is wrong. you typically mock services but often more. here however, person will hardly require being mocked.