[英]Skip the SetUp method only for a particular test in NUnit?
我有一個測試,在運行測試之前我不需要運行SetUp
方法(用[SetUp]
)。 我需要為其他測試運行SetUp
方法。
是否有可以使用的不同屬性或基於非屬性的方法來實現此目的?
您還可以添加類別並檢查設置中的類別列表:
public const string SKIP_SETUP = "SkipSetup";
[SetUp]
public void Setup(){
if (!CheckForSkipSetup()){
// Do Setup stuff
}
}
private static bool CheckForSkipSetup() {
ArrayList categories = TestContext.CurrentContext.Test
.Properties["_CATEGORIES"] as ArrayList;
bool skipSetup = categories != null && categories.Contains( SKIP_SETUP );
return skipSetup ;
}
[Test]
[Category(SKIP_SETUP)]
public void SomeTest(){
// your test code
}
您應該為該測試創建一個新類,它只需要設置(或缺少設置)。
或者,您可以將設置代碼解釋為所有其他測試調用的方法,但我不建議使用此方法。
您可以在基類中使用主SetUp
:
[SetUp]
public virtual void SetUp()
{
// Set up things here
}
...然后在您擁有不應運行SetUp
代碼的測試的類中覆蓋它:
[SetUp]
public override void SetUp()
{
// By not calling base.SetUp() here, the base SetUp will not run
}
以下是我建議您完成所需內容的代碼:
public const string SKIP_SETUP = "SkipSetup";
private static bool CheckForSkipSetup()
{
string category = string.Empty;
var categoryKeys = TestContext.CurrentContext.Test.Properties.Keys.ToList();
if (categoryKeys != null && categoryKeys.Any())
category = TestContext.CurrentContext.Test.Properties.Get(categoryKeys[0].ToString()) as string;
bool skipSetup = (!string.IsNullOrEmpty(category) && category.Equals(SKIP_SETUP)) ? true : false;
return skipSetup;
}
[SetUp]
public void Setup()
{
// Your setup code
}
[Test]
public void WithoutSetupTest()
{
// Code without setup
}
[Test]
[Category(SKIP_SETUP)]
public void CodeWithSetupTest()
{
// Code that require setup
}
我不相信你能做到這一點,它將涉及知道什么樣的測試即將運行,我認為不可能。
我建議你把它放在一個不同的[TestFixture]中
這是我建議用於完成你想要的代碼。
public const string SKIP_SETUP = "SkipSetup";
現在添加以下方法:
private static bool CheckForSkipSetup()
{
var categories = TestContext.CurrentContext.Test?.Properties["Category"];
bool skipSetup = categories != null && categories.Contains("SkipSetup");
return skipSetup;
}
現在檢查條件如下:
[SetUp]
public async Task Dosomething()
{
if (!CheckForSkipSetup())
{
}
}
在測試用例中使用這些如下:
[Test]
[Category(SKIP_SETUP)]
public async Task Mywork()
{
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.