FakeItEasy - how to test a virtual method
I am using FakeItEasy to fake a class to do the following unit test. When I debug the unit test step by step, noticed that it will not go into the original method -> IsOrderHasToBeCharged (). Instead, it always returns the return value as False. Is it because the method is marked as virtual in the working class? Is there any other way to unit test this method?
source to share
When I debug the unit test step by step, noticed that it will not go into the original method -> IsOrderHasToBeCharged (). Instead, it always defaults to the return value as False. Is it because the method is marked as virtual in the working class?
Yes. That's for sure. When FakeItEasy creates a fake, it intercepts all calls to virtual methods and provides its own implementation, as explained in Signed members are faked .
If you want the original method to be IsOrderHasToBeCharged
called, you can set up fake to call the base method . This can be done for a single method, for example:
A.CallTo(() => switchHandler.IsOrderHasToBeCharged(payCode, amount))
.CallsBaseMethod();
or for each spoofing method at creation time:
var switchHandler = A.Fake<ChargeProcessorSwitchHandler>(
options => options.CallsBaseMethods());
Any of these will result in the original being IsOrderHasToBeCharged
called.
However , I am forced to point out that this is probably not the best approach for this particular test. In general, spoofing the system under test is a bad idea, as it can introduce confusion, similar to what you have already seen. In general, isolation frames ("fake frames") should be used to spoof the types with which the system under test interacts. Then the actual system under test is tested and executed.
ChargeProcessorSwitchHandler
Has no coauthors in this case , so I think you'd better replace
var switchHandler = A.Fake<ChargeProcessorSwitchHandler>();
from
var switchHandler = new ChargeProcessorSwitchHandler();
Then you can exclude FakeItEasy from the test entirely.
source to share