Mocks are to be used as replacement for dependencies around what you are trying to test.
Concerning your test, just test the actual exposed behavior of your class, meaning don't try to use private methods and setters. In any case, mokcing the class to test is not a valid approach.
For instance :
If you want to test the Test
class :
[TestClass]
public class TestTests
{
[TestMethod]
public void Calc_WhenPropIsSetTo5_Returns10()
{
/**
* Seems this is what you want to test (see name of methods),
* and I don't think it is a good idea, as your setter is private.
* Since it's not a "public" behavior, you could either
*
* a) have the setter as internal for testing purposes,
*
* b) (my recommendation) go for the two other tests below instead;
* this will actually test the exposed behavior of the class.
*
* c) circumvent the accessibility (by using a library or using
* Reflection directly) to set the value of the prop.
* See your own answer for an example.
*/
}
[TestMethod]
public void Calc_WhenCreatedWith5_Returns10()
{
// Arrange
var testSubject = new Test(5); // if the prop is set by constructor... otherwise arrange in the proper way.
// Act
var actualResult = testSubject.Calc();
// Assert
Assert.AreEqual(expected: 10, actualResult)
}
[TestMethod]
public void Prop_WhenCreatedWith5_IsSetTo5()
{
// Arrange
var testSubject = new Test(5);
// Act
var actualResult = testSubject.Prop;
// Assert
Assert.AreEqual(expected: 5, actualResult)
}
}
If you want to test something that uses ITest.Calc()
,
then you should, in your actual code,
1 - depend on the interface ITest
, not on implementation Test
2 - have the dependency injected to the class being tested, so that you can replace the usual implementation Test
by Mock<ITest>.Object()
public class ClassThatUsesTest
{
private readonly ITest _test;
public ClassThatUsesTest(ITest test)
{
_test = test;
}
public int SomeFunction()
{
if (_test.Calc() == 10)
{
return 42;
}
else
{
return 0;
}
}
}
[TestClass]
public class ClassThatUsesTestTests
{
[TestMethod]
public void SomeFunction_WhenTestCalcReturns10_Returns42()
{
// Arrange
var testMock = new Mock<ITest>();
testMock.Setup(x => x.Calc()).Returns(10);
var testSubject = new ClassThatUsesTest(testMock.Object);
var expectedResult = 42;
// Act
var actualResult = testSubject.SomeFunction();
//
Assert.AreEqual(expectedResult, actualResult);
}
}
In the last example, you can see the mocks help us to isolate the test without depending on the actual implementation details of the Test
class. Even if suddenly the actual Test
is broken or change (e.g. you need to pass 6 instead of 5 to get 10), the test method doesn't care.