Mocking internal class without interface

86 Views Asked by At

I am trying to mock internal class for unit tests, due to some circular dependency I will not be able to use interface of this class to mock it, I also added unit test assembly name (made sure I am using correct assembly name from properties) to AssemblyInfo.cs of this project with InternalsVisibleTo , also added AssemblyInfo to csproj using <Compile Include="Properties\AssemblyInfo.cs" />, this makes class visible to test file but its not visible for mocking

NotSupportedException: Type to mock must be an interface, a delegate, or a non-sealed, non-static class.

I want to create mock of this class to do setup on other method in this class which I am not testing

1

There are 1 best solutions below

0
On

In order to be able to replace a concrete dependency with a Test Double, there must be some kind of polymorphism in place. There must be something to override or implement: abstract or virtual members, or an interface.

The exception message already tells you that:

Type to mock must be an interface, a delegate, or a non-sealed, non-static class.

It has nothing to do with whether the class in question is internal or public.

due to some circular dependency I will not be able to use interface of this class to mock it

Nothing prevents you from using interfaces, even in the presence of circular dependencies. See e.g. DIPPP for ways to deal with dependency cycles.

All that said, code will tend to be easier to maintain when it doesn't have circular dependencies, and when you only test against the public API.