[英]How to write nunit test case(c#) for generic class which inherits another class
我正在嘗試為一個通用 class 編寫 Nunit 測試用例,如下所示。 但是我不知道我應該如何編寫測試用例,因為像下面這樣的編寫甚至無法運行,有人可以幫忙嗎?
我的主要 class 是這樣的:-
public class TestController<T> : ControllerBase
{
private const string STATUS_OK_MESSAGE = "OK";
[HttpGet]
public ContentResult Get()
{
*** Some logic here *****
return Content(STATUS_OK_MESSAGE);
}
}
我嘗試過的測試用例如下:-
[TestFixture]
public class Test1<T> where T : class
{
TestController testController;
[OneTimeSetUp]
public void OneTimeSetup()
{
testController= new TestController();
}
[Test]
public void Get()
{
var result = (ContentResult)testController.Get();
Assert.AreEqual("OK", "OK");
}
}
您不會在任何地方告訴 NUnit T
使用什么。 where
子句適用於編譯器,而不適用於 NUnit。 因此,NUnit 無法構造您的夾具,因為它可能只為特定的T
構造。
更根本的是,在您的測試代碼中,您沒有使用T
。 如果 controller class 是通用的,那么您必須在代碼中使用 TestController。 或者使用特定的 TestController 類型。
基本上,我們需要知道為什么您希望您的測試是通用的。 或者你是否真的這樣做。 您的應用程序中是否有多個 TestController 類型? 還是只有一個? 如果只有一個,您根本不需要通用測試。
如果您編輯您的問題以解釋更多您想要做的事情,我將在此處添加一些建議的代碼。 但是您可能會嘗試做幾件不同的事情,並且每件事情的代碼都不同。
更新
根據您需要多個控制器的信息,編寫測試的一種方法是......
[TestFixture(typeof(TestController<Class1>)]
[TestFixture(typeof(TestController<Class2>)]
public class Test1<T> where T : ControllerBase, new()
{
T testController;
[OneTimeSetUp]
public void OneTimeSetup()
{
testController = new T();
}
[Test]
public void Get()
{
var result = (ContentResult)testController.Get();
Assert.AreEqual("OK", "OK");
}
}
僅當您的控制器都具有默認構造函數時,此方法才有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.