gpt4 book ai didi

c# - 具有无参数构造函数的 NUnit TestFixture

转载 作者:太空宇宙 更新时间:2023-11-03 15:38:59 25 4
gpt4 key购买 nike

您如何解决您尝试定义的 TestFixture 需要引用没有无参数构造函数的类型的情况?

我正在尝试测试具有多个实现的接口(interface)。在 NUnit 文档中,它展示了如何使用这样的泛型进行设置(我可以在其中定义多种实现类型):

[TestFixture(typeof(Impl1MyInterface))]
[TestFixture(typeof(Impl2MyInterface))]
[TestFixture(typeof(Impl3MyInterface))]
public class TesterOfIMyInterface<T> where T : IMyInterface, new() {

public IMyInterface _impl;

[SetUp]
public void CreateIMyInterfaceImpl() {
_impl = new T();
}
}

问题的出现是因为 Impl1MyInterface、Impl2MyInterface 等没有无参数构造函数,所以当 NUnit 试图发现可用的测试用例时,我得到这个错误(并且测试没有出现在 VS 中):

Exception System.ArgumentException, Exception thrown discovering tests in XYZ.dll

有没有办法解决这个问题?定义无参数构造函数没有意义,因为我的代码需要这些值才能工作。

最佳答案

除了使用 new T() 来实例化您的对象,您还可以使用 依赖注入(inject)容器 来为您实例化它们。下面是一个使用 Microsoft Unity 的示例:

[SetUp]
public void CreateIMyInterfaceImpl() {
var container = new UnityContainer();

// Register the Types that implement the interfaces needed by
// the Type we're testing.
// Ideally for Unit Tests these should be Test Doubles.
container.RegisterType<IDependencyOne, DependencyOneStub>();
container.RegisterType<IDependencyTwo, DependencyTwoMock>();

// Have Unity create an instance of T for us, using all
// the required dependencies we just registered
_impl = container.Resolve<T>();
}

关于c# - 具有无参数构造函数的 NUnit TestFixture,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30868423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com