【发布时间】:2009-07-28 13:46:09
【问题描述】:
我有一个测试,我不需要在运行测试之前运行SetUp 方法(归因于[SetUp])。我需要为其他测试运行 SetUp 方法。
是否可以使用不同的属性或非基于属性的方式来实现这一点?
【问题讨论】:
标签: unit-testing nunit
我有一个测试,我不需要在运行测试之前运行SetUp 方法(归因于[SetUp])。我需要为其他测试运行 SetUp 方法。
是否可以使用不同的属性或非基于属性的方式来实现这一点?
【问题讨论】:
标签: unit-testing nunit
您还可以在设置中添加类别并检查类别列表:
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
}
【讨论】:
这是我建议的用于完成您想要的代码。
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()
{
}
【讨论】:
我不相信你能做到这一点,这需要知道将要运行什么测试,而我认为这是不可能的。
我建议你把它放在不同的 [TestFixture] 中
【讨论】:
根据@MiGro 回答here,我使用另一个测试命名空间和它自己的[OneTimeSetUp] 来实现,我想开始以不同于其他方式测试的类的不同实现。
【讨论】: