FakeItEasy and Protected methods

By | April 24, 2015
I often find myself dealing with protected methods in the unit testing land.

Now if the method is public then this works

A.CallTo(() => fakeObject.MethodUnderTest()).MustHaveHappened();

However when the method is protected then it does not fly. With FakeItEasy you have to take the different approach.

A.CallTo(fakeObject).Where(x => x.Method.Name ==”MethodUnderTest”).MustHaveHappened();

And needless to say, the method under test should be a virtual method.

There is a brute force method also possible. Make the class under test as internal and add it to the project under test (e.g. in Properties\AssemblyInfo.cs). “Your.Test.Assembly.Name” would be the test assembly. Then you can get access to protected and private members.

using System.Runtime.CompilerServices;  [assembly:InternalsVisibleTo("Your.Test.Assembly.Name")]

But this is discouraged by many. You are the person to decide.

More information at this StackOverFlow thread.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.