5

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?

Community
  • 1
  • 1
Sammy S.
  • 1,280
  • 1
  • 16
  • 31
  • 1
    you don't IMO - you can create a Dummy-class and use Moq internally there - see once you use new you lose the connection to your fake anyway - and BTW: it's seems to be a bit of a smell if you use `new` there – Random Dev Sep 16 '15 at 08:20
  • Instead of using the `new()` constraint, you should add a `Func create` parameter to `DoSomething()` and call that to create the object rather than `new`ing it up. Exactly how to create the object is not something `DoSomething()` should have to know about. – Matthew Watson Sep 16 '15 at 08:24
  • `DoSomething` is a static method so you won't be able to fake it using `moq`... Your effort to mock the `new()` constraint is worthless.... – Old Fox Sep 16 '15 at 08:44
  • 1
    @OldFox He's trying to test it, not mock it. – Rawling Sep 16 '15 at 08:44
  • thanks @Rawling somehow I skipped the first line... the solution I can offer is to create a class without a behavior(not an `abstract class` just empty method and return defaults) and make all the methods in the class `virtual`, then you can use `moq` in each one of the `UT` to simulate the behavior you wants... – Old Fox Sep 16 '15 at 09:08
  • 1
    this seems like one of those instances where the *mock* is way more complicated than the tested code ... I would suggest rethinking the design ... – Random Dev Sep 16 '15 at 09:25

1 Answers1

1

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

Dror Helper
  • 30,292
  • 15
  • 80
  • 129
  • You are right. Essentially, I'm abusing the `new()` constraint to avoid the more explicit solution -- passing a constructor function. – Sammy S. Oct 23 '15 at 07:45