Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking the 'new()' constraint with Moq

I want to test a function with the type signature

public static void DoSomething<T>(T something)
    where T : class, IInterfaceA, IInterfaceB, new()

which uses new T() internally.

I'm having problems creating a mock for T. Thanks to another question, I already found a solution for mocking multiple interfaces. However, I'm unable to create a mock satisfying the new() constraint. How do I solve this using Moq?

like image 336
Sammy S. Avatar asked Nov 10 '22 05:11

Sammy S.


1 Answers

You have two options:

  1. Use unconstraint mocking framework. In .NET it means either Isolator or JustMock. Both use IL weaving to inject code during runtime and can fake/mock object which are created inside the production code.
  2. Split DoSomething logic and use dependency injection instead of creating the object as part of the logic.

Choosing between the two depends on how hard it is to split the logic, whether the remaining code has enough "meat" in it and if you're willing to pay for a Mocking framework that can fake new

like image 126
Dror Helper Avatar answered Nov 14 '22 22:11

Dror Helper