Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock protected virtual members in FakeItEasy?

Moq allows mocking protected virtual members (see here). Is it possible to do the same in FakeItEasy?

like image 526
Daniel Rose Avatar asked Mar 18 '11 11:03

Daniel Rose


2 Answers

It can be done, however it can not be done out of the box. The trick is to implement IFakeObjectCallRule and add it to your fake through Fake.GetFakeManager(foo).AddRule(myRule).

I'm thinking of implementing this feature though, it would be something like this:

A.CallTo(foo).WhereMethod(x => x.Name == "MyProtectedMethod").Returns("whatever");

The syntax is not quite refined yet though.

Edit The feature mentioned above is now implemented:

A.CallTo(foo).Where(x => x.Method.Name == "MyProtectedMethod").WithReturnType<int>().Returns(10);
like image 120
Patrik Hägne Avatar answered Nov 20 '22 04:11

Patrik Hägne


In addition to Patrik's answer, I thought it would be relevant in this post to add a tip of how you could mock a protected property member:

A.CallTo(foo).Where(x => x.Method.Name == "get_MyProtectedProperty").WithReturnType<int>().Returns(10);

This is actually how reflection treats 'getter' methods of properties.

Hope it helps :)

like image 33
Shay Ben-Sasson Avatar answered Nov 20 '22 05:11

Shay Ben-Sasson