Welcome to Typemock Answers. Here you can ask and receive answers from other community members. And if you liked or disliked an answer or thread: react with an up- or downvote Enjoy!

Mocking a private function in a base class, VB.NET

0 votes

I am evaluating TypeMock Isolator for potential purchase for my development team, which is tasked with working on some gnarly legacy code, much of it VB.NET, so I'm very intrigued about the "mock everything" ethos, and TypeMock's abilities in this area. In my evaluation against our codebase, I've encountered the following scenario, and I'd love it if someone could explain to me the right way to pull of this particular mock, on a VB.NET base class.

This streamlined example demonstrates my issue:

Public MustInherit Class BaseClass
    Public Function PublicFunction() As Boolean
        Return PrivateFunction()
    End Function

    Private Function PrivateFunction() As Boolean
        Return True
    End Function
End Class

Public Class InheritingClass
    Inherits BaseClass

End Class

Public Class TestIt

    <Test(), Isolated()>
    Public Sub ShouldBeAbleToMockPrivateFunctionOnBaseClass()
        Dim mock As Mock = MockManager.Mock(GetType(BaseClass))
        mock.ExpectAndReturn("PrivateFunction", False)

        Dim ic As New InheritingClass()

        Assert.AreEqual(False, ic.PublicFunction())
    End Sub

End Class

The test fails because the mock I've created here doesn't seem to be acknowledged on the base class. I've tried this same style of test on a more straightforward class that does not inherit, and that works fine. Is there a change I can do to this example that will allow me to mock the private function of the base class, without having to refactor the class' access modifiers in any way?

Thanks in advance!

asked Jun 5, 2014 by ZynxAR (140 points)

1 Answer

0 votes

Please see the following example on how to solve this issue:
public void TestMethod1()
    var mock = Isolate.Fake.AllInstances<BaseClass>();
    Isolate.NonPublic.WhenCalled(mock , "PrivateFunction" ).WillReturn(false);

    var ic = new InheritingClass();


The important thing here is to fake the creation of the future instance of InheritingClass by using "Fake.AllInstances".

I recommend you to use the C# API since it is better supported and has several extra features.


Alex Galin | Support Team

answered Jun 15, 2014 by alex (17,910 points)