gabbi soloer
gabbi soloer

Reputation: 453

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 foo()
   {
       ...
       base.foo();
       ...
   }
}

How can I test the method foo in MyDerived Class without executing the base.foo() method ?

Upvotes: 3

Views: 2377

Answers (4)

Morten
Morten

Reputation: 3854

If you have the need not to execute your base method in the test, there is something wrong in your design.

Upvotes: 1

ppiotrowicz
ppiotrowicz

Reputation: 4614

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.

Upvotes: 1

diversemix
diversemix

Reputation: 569

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.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500575

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...)

Upvotes: 13

Related Questions