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.
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/
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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With