How can I write Unit Tests for a method that has a call to a base method in the base object
I have the following code:
class MyBase
{
public virtual void foo()
{ ... }
}
class MyDerived : MyBase
{
public override void fo开发者_运维百科o()
{
...
base.foo();
...
}
}
How can I test the method foo in MyDerived Class without executing the base.foo() method ?
You can't, basically. Test the base class method separately so that you have confidence in that, and then you can test the derived class relying on the base class behaviour.
(This is another case where composition gives more control than inheritance - if your derived class composed the base class instead, you could use a mock or whatever instead. Not that it's always appropriate of course, but...)
How about refactoring MyDerived to have methods DoPreFoo() and DoPostFoo(). In this way foo can be rewritten to call these functions and you can use them for your unit tests. However this feels a bit ugly. I have the feeling that MyDervied needs to aggregate MyBase and not derive from it if the functionality needs to be tested separately.
Short answer is: you can't. Because you cannot "mock away" this dependency.
Maybe TypeMock Isolator has some magic profile API tricks that can help here, but I'm not sure.
If you have the need not to execute your base method in the test, there is something wrong in your design.
精彩评论