Reputation: 33
I'm new to Testing in C# and I'm trying to test a method that only increments some passed integer value (when it's called with 5 it returns 6). What am I doing wrong here? result
is always 0.
public void TestMethod2()
{
//Act
int numberToCheck = 5;
mock.CallBase = true;
mock.Setup(x => x.CalculateTest(numberToCheck)).Returns(6);
int result = mock.Object.CalculateTest(It.IsAny<int>());
int expected = numberToCheck + 1;
//Assert
Assert.AreEqual(expected, result);
}
Upvotes: 0
Views: 49
Reputation: 5156
Your test appears to be a little pointless. It looks like your mocking the very thing you want to test. Normally you mock everything else around the bit you want to test a bit like this:
//This is normally something like a repository that you link to from a service.
//You want the repo to return mocked data so you can see what your service method
//actually does in a set circumstance.
private Mock<ISomethingEffectingYourTestsToMock> _myMockObject;
private IMyServiceUnderTest _sut;
[TestInitialize]
public void Init()
{
_myMockObject = new Mock<ISomethingEffectingYourTestToMock>(); //mock
_sut = new MyServiceUnderTest(your parameters); //real instance
}
[TestMethod]
public void SomeOtherMethod_should_return_23_if_input_is_20()
{
var mockRepoOutput = 6;
this._myMockObject.Setup(r => r.someMethod(It.IsAny<int>())).Returns(mockRepoOutput);
var inputParam = 20;
var expectedResult = 23;
var result = _sut.SomeOtherMethod(inputParam);
Assert.AreEqual(expectedResult, result);
}
Something to consider when starting to write a suite of unit tests are things like common mock data, mock setup etc. You can save a lot of time if you don't have to setup mock data objects in every test and instead can just call a method to get what you need.
Upvotes: 1