Nunit:如何在 NUnit 属性中有参数

Nunit: How to have an argument in NUnit attribute

我正在尝试调用具有 NUnit 属性的参数我收到错误

Invalid signature for SetUp or TearDown method: cleanup

我的脚本:

[Test]
public void Test()
{
    TWebDriver driver = new TWebDriver();
    driver.Navigate().GoToUrl("http://www.google.com");
    StackFrame stackFrame = new StackFrame();
    MethodBase methodBase = stackFrame.GetMethod();
    string Name = methodBase.Name;
    cleanup(Name);
}

[TearDown]
public void cleanup(string testcase)
{
    string path = (@"..\..\Passor\");
    DateTime timestamp = DateTime.Now;
    if (TestContext.CurrentContext.Result.Status == TestStatus.Failed)
    {
        File.WriteAllText(Path.Combine(path, "Failed" + ".txt"), "Failed " + testcase);
    }
    else
    {
        File.WriteAllText(Path.Combine(path, "Passed" + ".txt"), "Passed " + testcase);
    }
}   

如果这不可能。还有其他方法可以在清理方法中添加methodname吗?

你不需要调用 cleanup 方法,它会自动调用,你需要做的是在 TestContextclass.

例如:

使用字段:

[TestFixture]
public class GivenSomeTest
{
    private string _testCase;
    [Test]
    public void Test()
    {
        StackFrame stackFrame = new StackFrame();
        MethodBase methodBase = stackFrame.GetMethod();
        _testCase = methodBase.Name;
        TWebDriver driver = new TWebDriver();
        driver.Navigate().GoToUrl("http://www.google.com");

    }

    [TearDown]
    public void cleanup()
    {
        string path = (@"..\..\Passor\");
        DateTime timestamp = DateTime.Now;
        if (TestContext.CurrentContext.Result.Status == TestStatus.Failed)
        {
            File.WriteAllText(Path.Combine(path, "Failed" + ".txt"), "Failed " + _testCase);
        }
        else
        {
            File.WriteAllText(Path.Combine(path, "Passed" + ".txt"), "Passed " + _testCase);
        }
    }   
}

使用TestContext:

[TestFixture]    
public  class GivenSomeTest
{

    [Test]
    public void Test()
    {
        StackFrame stackFrame = new StackFrame();
        MethodBase methodBase = stackFrame.GetMethod();
        TestContext.CurrentContext.Test.Properties.Add("testCase",methodBase.Name);
        TWebDriver driver = new TWebDriver();
        driver.Navigate().GoToUrl("http://www.google.com");
    }

    [TearDown]
    public void cleanup()
    {
        var testCase = TestContext.CurrentContext.Test.Properties["testCase"];
        string path = (@"..\..\Passor\");
        DateTime timestamp = DateTime.Now;
        if (TestContext.CurrentContext.Result.Status == TestStatus.Failed)
        {
            File.WriteAllText(Path.Combine(path, "Failed" + ".txt"), "Failed " + testCase);
        }
        else
        {
            File.WriteAllText(Path.Combine(path, "Passed" + ".txt"), "Passed " + testCase);
        }
    }   
}