![](/img/trans.png)
[英]Is there a way to pass delegates to a NUnit TestCase or TestFixture?
[英]NUnit TestFixture and TestCase
我必須用 NUnit 編寫一些集成測試來測試 HTTP 端點。 這意味着 URL 應該在所有測試方法之間共享。
[TestFixture("http://my.endpoint.com")]
public class TestSuiteOne
{
[TestCase(10, 20, Expected = 30)]
[TestCase(20, 30, Expected = 50)]
public int TestA(int a, int b, HttpResponseMessage sut)
{
// AAA.
}
[TestCase("XXX", "YYY", Expected = "ABC")]
public int TestA(string a, string b, HttpResponseMessage sut)
{
// AAA.
}
}
要在來自測試套件屬性的每個測試運行中獲取 SUT 值,我知道兩個選項:
選項 A(從類屬性中讀取 SUT)
public abstract class TestSuiteBase
{
protected(string endpoint)
{
Sut = endpoint;
}
protected HttpResponseMessage Sut { get; }
}
[TestFixture("http://my.endpoint.com")]
public class TestSuiteOne : TestSuiteBase
{
public TestSuiteOne(string endpoint) : base(endpoint)
{
}
[TestCase(10, 20, Expected = 30)]
[TestCase(20, 30, Expected = 50)]
public int TestA(int a, int b)
{
// act (read content/response code/headers/etc); Making a call I do not consider as act.
var actual = Sut.DoSomething();
// assert
}
[TestCase("XXX", "YYY", Expected = "ABC")]
public int TestA(string a, string b)
{
// act (read content/response code/headers/etc); Making a call I do not consider as act.
var actual = Sut.DoSomething();
// assert
}
}
選項 B(攔截測試方法調用)
public class MyTestCase: TestCaseAttribute
{
public MyTestCase(params object[] args) : base(Resize(args))
{
}
// I do resize before method call because VS Test Adapters discover tests to show a list in the test explorer
private static object[] Resize(params object[] args)
{
Array.Resize(ref args, args.Length + 1);
args[args.Length - 1] = "{response}";
return args;
}
}
public abstract class TestSuiteBase
{
[SetUp]
public void OnBeforeTestRun()
{
var ctx = TestContext.CurrentContext;
var args = ctx.Test.Arguments;
// Making a call I do not consider as act.
args[args.Length - 1] = MakeCallAndGetHttpResponseMessage(args);
}
}
[TestFixture("http://my.endpoint.com")]
public class TestSuiteOne : TestSuiteBase
{
[MyTestCase(10, 20, Expected = 30)]
[MyTestCase(20, 30, Expected = 50)]
public int TestA(int a, int b, HttpResponseMessage sut)
{
// act (read content/response code/headers/etc); Making a call I do not consider as act.
var actual = sut.DoSomething();
// assert
}
[MyTestCase("XXX", "YYY", Expected = "ABC")]
public int TestA(string a, string b, HttpResponseMessage sut)
{
// AAA.
}
}
有沒有更方便的方法如何將來自 TestFixture 的值與 TestCase 結合起來?
由於您將端點字符串放在TestFixtureAttribute
,我將假設
您的示例中唯一缺少的是一個構造函數,它將接受您提供的參數。 只需添加類似...
public TestSuiteOne(string url)
{
Sut = endpoint;
}
只要您將Sut
設為只讀屬性或字段,您的任何測試用例都無法更改它,無論它們是按順序運行還是並行運行。
您提供的兩個選項對我來說似乎都過於復雜,至少就您對問題的解釋而言。 第一個最接近這個答案。
當然,您完全有可能對網站做其他事情,這會導致並行(甚至順序)測試相互干擾。 不要那樣做。 :-) 說真的,共享驅動程序與共享字符串完全不同,但這是一個不同的問題。
順便說一句,IMO,您和您的團隊應該習慣一個或另一個測試框架。 您提到的生命周期問題並不是 NUnit 和 xUnit 之間唯一的細微差別!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.