Reputation: 1747
I have a property on an instance of a class that essentially sums other properties on that class. How can I mock the "known" properties but still call the method on the instance? This obviously doesn't work but hopefully gets my question across:
public void TestSum()
{
// Arrange
var classToTestInstance = new ClassToTest();
classToTestInstance.MyProp1 = new Mock().Returns(5); // MyProp1 is private set;
classToTestInstance.MyProp2 = new Mock().Returns(3); // Same
// There's not really an Act here...
// Assert; Total is the actual property I want to test
classToTestInstance.Total.Should().Be(8);
}
I could instantiate an actual ClassToTest and do the functions that put it in the correct state for my Total test, but then I'm not just testing the Total functionality.
Upvotes: 1
Views: 155
Reputation: 1500525
I could instantiate an actual ClassToTest and do the functions that put it in the correct state for my Total test, but then I'm not just testing the Total functionality.
No, but if you feel you need to test that functionality separately, then perhaps it shouldn't be part of the same object.
Personally I'd do exactly that: get the object into the right state, and then test Total
. Don't forget that you can have plenty of dedicated unit tests for the functions which you'll also use to get the object into the right state.
While there are certainly some mock frameworks which would allow you to mock this behaviour while testing your original Total
behaviour, I would personally steer clear of mocking the same class you're trying to test - and indeed I'd avoid overusing mocking at all. It's great in the right places, but where it's just as easy to use the real thing (and that "real thing" is tested separately) I'd do so.
Upvotes: 3