Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is purpose of mocking a class like Calculator?

I've been using TDD for some time but now I'm looking at mocking frameworks and I don't get some things. This question might sound stupid for someone experienced but I just don't get it. The library I use is Moq + xUnit.

Question

What's the point of testing Calculator class if I explicitly say that 2 + 2 will return 4 on this line mock.Setup(x => x.Add(2, 2)).Returns(4); and then assert it?

Of course result will be 4, I just "forced" it to return 4 in few lines above the test itself. And now even in my implementation if I do return a * b; instead of return a + b; the test will pass.

Here is another example of this same calculator tests. http://nsubstitute.github.io/

Example Code

namespace UnitTestProject1
{
    using Xunit;
    using Moq;

    public class CalculatorTests
    {
        private readonly ICalculator _calculator;

        public CalculatorTests()
        {
            var mock = new Mock<ICalculator>();

            mock.Setup(x => x.Add(2, 2)).Returns(4);
            mock.Setup(x => x.Subtract(5, 2)).Returns(3);

            this._calculator = mock.Object;
        }

        [Fact]
        public void Calculator_Should_Add()
        {
            var result = _calculator.Add(2, 2);

            Assert.Equal(4, result);
        }

        [Fact]
        public void Calculator_Should_Subtract()
        {
            var result = _calculator.Subtract(5, 2);

            Assert.Equal(3, result);
        }
    }

    public class Calculator : ICalculator
    {
        public int Add(int a, int b)
        {
            return a + b;
        }

        public int Subtract(int a, int b)
        {
            return a - b;
        }
    }

    public interface ICalculator
    {
        int Add(int a, int b);
        int Subtract(int a, int b);
    }
}
like image 931
Stan Avatar asked May 07 '14 12:05

Stan


1 Answers

The purpose is to be able to test classes depending on calculator without having the calculator is self. In your test you know that the calculator can't be the cause of failure, because is returning the correct answer.

By isolating the code under test you will be able to test real units of code. And also see exactly what is causing your test failure.

like image 132
Peter Avatar answered Sep 27 '22 15:09

Peter