Moq - how to mock a protected method of an internal class with no parameter-less constructor
Problem statement
I have a class which:- Is internal in a separate assembly from tests (InternalsVisibleTo is set, so the test project sees the class).
- Has no parameter-less constructor.
- Has a protected method which I want to mock (only this method, I want to use the others).
There are several problems to solve here:
- How to mock internal class?
- How to mock a class with no parameter-less constructor
- How to mock only some of the methods in a class?
- How to mock protected method?
Solution
How to mock internal class?
The solution I've found in this article.
Basically, when the class is internal you should make it visible to the test
project by applying assembly attribute InternalsVisibleTo
. But Moq
is one another assembly that can't see what is inside tested project. So I need
to apply another attribute:
Now I can mock an internal class from within a test project.
How to mock a class with no parameter-less constructor
The answer lies in the Mock class constructor (and in this StackOverflow answer.)
In case of my contructor I need to pass the parameter to the constructor of Mock class:
How to mock only some of the methods in a class?
This is also known as "Partial Mock". This is described in the official QuickStart document of Moq. in the section "Customizing Mock Behavior". What I need is just to add:
How to mock protected method?
One more time QuickStart document comes to the rescue (). Moq doesn't provide intellisense for protected methods. I need to: