[英]NUnit TestFixture with no-arg constructors
在要定義的TestFixture需要引用沒有no-arg構造函數的類型的情況下,如何解決?
我正在嘗試測試具有多個實現的接口。 從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等沒有no-arg構造函數,因此當NUnit嘗試發現可用的測試用例時,我會收到此錯誤(並且測試未在VS中顯示):
異常System.ArgumentException,在XYZ.dll中發現測試時引發異常
有辦法解決這個問題嗎? 定義無參數構造函數是沒有意義的,因為我的代碼需要這些值才能起作用。
代替使用new T()
實例化對象,可以使用dependency injection container
為您實例化它們。 這是使用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>();
}
就像@Steve Lillis在回答中所說的那樣,您需要停止使用new T()
。 執行此操作時,無需在泛型上使用new
約束。 一種選擇是使用IOC容器,如史蒂夫建議的解決城堡中的依賴關系一樣,使用Castle Windsor / Unity。
您沒有說實現的構造函數采用什么參數,但是如果它們都相同,則可以選擇使用Activator.CreateInstance
代替。 因此,如果所有構造函數都使用整數和字符串,則代碼將如下所示:
[TestFixture(typeof(Impl1MyInterface))]
[TestFixture(typeof(Impl2MyInterface))]
[TestFixture(typeof(Impl3MyInterface))]
public class TesterOfIMyInterface<T> where T : IMyInterface {
public IMyInterface _impl;
[SetUp]
public void CreateIMyInterfaceImpl() {
int someInt1 = 5;
string someString = "some value";
_impl = (T)Activator.CreateInstance(typeof(T), new object[] { someInt1, someString });
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.