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

本文关键字:属性 有一个 参数 NUnit Nunit | 更新日期: 2023-09-27 18:37:01

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

SetUpTearDown方法的签名无效: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吗?

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

你不需要

调用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);
        }
    }   
}
相关文章: