简体   繁体   English

使用Moq模拟'new()'约束

[英]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. 它在内部使用new T()

I'm having problems creating a mock for T . 我在为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. 但是,我无法创建满足new()约束的模拟。 How do I solve this using Moq? 我如何使用Moq解决这个问题?

You have two options: 您有两种选择:

  1. Use unconstraint mocking framework. 使用无约束模拟框架。 In .NET it means either Isolator or JustMock. 在.NET中,它意味着Isolator或JustMock。 Both use IL weaving to inject code during runtime and can fake/mock object which are created inside the production code. 两者都使用IL编织在运行时注入代码,并且可以伪造/模拟在生产代码中创建的对象。
  2. Split DoSomething logic and use dependency injection instead of creating the object as part of the logic. 拆分DoSomething逻辑并使用依赖注入,而不是将对象创建为逻辑的一部分。

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 在两者之间进行选择取决于拆分逻辑的难度,剩下的代码是否有足够的“肉”,以及你是否愿意支付可以伪造的Mocking框架

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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