简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM