C# 使用NUnit——如何获取当前正在执行的测试夹具和名称?
我想在我使用的助手方法中获取当前正在执行的NUnit测试。实际上,我们在这里使用NUnit进行集成测试,而不是单元测试。测试完成后,我们希望测试完成后清理一些日志文件。目前,我已经使用StackFrame类破解了这个问题:C# 使用NUnit——如何获取当前正在执行的测试夹具和名称?,c#,nunit,C#,Nunit,我想在我使用的助手方法中获取当前正在执行的NUnit测试。实际上,我们在这里使用NUnit进行集成测试,而不是单元测试。测试完成后,我们希望测试完成后清理一些日志文件。目前,我已经使用StackFrame类破解了这个问题: class TestHelper { string CurrentTestFixture; string CurrentTest; public TestHelper() { var callingFrame = new Sta
class TestHelper
{
string CurrentTestFixture;
string CurrentTest;
public TestHelper()
{
var callingFrame = new StackFrame(1);
var method = callingFrame.GetMethod();
CurrentTest = method.Name;
var type = method.DeclaringType;
CurrentTestFixture = type.Name;
}
public void HelperMethod()
{
var relativePath = Path.Combine(CurrentTestFixture, CurrentTest);
Directory.Delete(Path.Combine(Configurator.LogPath, relativePath));
}
}
[TestFixture]
class Fix
{
[Test]
public void MyTest()
{
var helper = new TestHelper();
//Do other testing stuff
helper.HelperMethod();
}
[Test]
public void MyTest2()
{
var helper = new TestHelper();
//Do some more testing stuff
helper.HelperMethod();
}
}
这很好,除了有些情况下我想让TestHelper类成为我的fixture的一部分,比如:
[TestFixture]
class Fix
{
private TestHelper helper;
[Setup]
public void Setup()
{
helper = new TestHelper();
}
[TearDown]
public void TearDown()
{
helper.HelperMethod();
}
[Test]
public void MyTest()
{
//Do other testing stuff
}
[Test]
public void MyTest2()
{
//Do some more testing stuff
}
}
我不能简单地将这个类变成一个全局的fixture,因为有时候单个测试会多次使用它,有时候一个测试根本不需要使用它。有时测试需要将特定属性附加到TestHelper。。。。诸如此类的事情
因此,我希望能够以某种方式获得当前正在执行的测试,而不必在我正在查看的数千个测试用例中手动重复夹具和测试的名称
有没有办法获得这样的信息?将
TestHelper
构造函数中的代码移动到HelperMethod
中就可以了
class TestHelper
{
public void HelperMethod()
{
string CurrentTestFixture;
string CurrentTest;
var callingFrame = new StackFrame(1);
var method = callingFrame.GetMethod();
CurrentTest = method.Name;
var type = method.DeclaringType;
CurrentTestFixture = type.Name;
var relativePath = Path.Combine(CurrentTestFixture, CurrentTest);
Directory.Delete(Path.Combine(Configurator.LogPath, relativePath));
}
}
从外观上看,您不能这样做,因为设置和拆卸时的堆栈帧不包括测试方法
[Test, TestHelper]
public void MyTest()
{
...
}
至于清理日志文件,看起来每个测试方法都需要一个日志文件。在这种情况下,最好是:
[Test]
public void MyTest()
{
using(new TestHelper())
{
... test goes here ...
}
}
[Test, TestHelper]
public void MyTest()
{
...
}
固定格式。添加的IDisposable添加了一个“实验性”TestContext类。它包含的属性之一是TestName。我还没有尝试过,所以我不知道该信息在拆卸方法中是否可用。否,因为在我的示例中,在拆卸中调用了helper方法。这就是说,我已经大大简化了这里的事情。真正的helper类可以在输出上指定断言。。。等等,需要在其中调用多个方法。这只是我在这里拼凑的一个简单示例。真正的测试类不能这样做,因为我需要能够访问它以从测试中添加内容。目标是消除我目前使用的堆栈框架攻击,而不是修复它。仅供参考,我已经测试了它,TestName和其他属性可以在TearDown方法中使用:
if(TestContext.CurrentContext.Test.Name==“MyTestName”)