I am trying to write unit test for the code shown below using Microsoft.Fakes.

As new to Microsoft.Fakes i am facing difficulty in mocking the call to abstract base class protected functional method

My base class:

public abstract class MyAbstractBaseClass
{
protected virtual int MyFunctionalBaseClassMethod(int parameter1)
{
return (parameter1 * parameter1);
}
}  

My child class:

public class MyChildClass : MyAbstractBaseClass
{
public int GetSquare(int parameter1) //(target method for unit test)
{
return MyFunctionalBaseClassMethod(parameter1); //(target method to mock using Fakes)
}
} 

I tried following unit test code for mocking, but didn't work:

var square = 10;
var stubMyAbstractBaseClass = new Fakes.StubMyAbstractBase()
{
MyFunctionalBaseClassMethod = (a) => { return square; }
};  

Note: My abstract base class protected method performs complex operations so i need to mock it. The above code is just a sample.

Any pointers would be appreciated!

1

There are 1 answers

1
doobop On

You need to stub out MyChildClass instead of the abstract class. This worked for me.

[TestMethod]
public void CheckAbstractClassStub()
{
    var myChild = new StubMyChildClass()
    {
        MyFunctionalBaseClassMethodInt32 = (num) => { return 49; }
    };

    int result = myChild.GetSquare(5);
    Assert.AreEqual(result, 49);
}

Edit: Yes, it is protected. As I mentioned above, you need to stub out the protected method in the derived class, MyChildClass. You have stubbed out the abstract class, there's no instance there and it will not get called. If you want to do it for all instances, you may be able to use Shims, but you're just making it more difficult at that point.

Here's my base class and subclass so you can compare.

public abstract class MyAbstractBaseClass
{
    protected virtual int MyFunctionalBaseClassMethod(int parameter1)
    {
        return (parameter1 * parameter1);
    }
}

public class MyChildClass : MyAbstractBaseClass
{
    public int GetSquare(int parameter1) //(target method for unit test)
    {
        return MyFunctionalBaseClassMethod(parameter1); //(target method to mock using Fakes)
    }
}

Here's a screen shot of the code stopped at a debug point

protected method returning stubbed value