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

时间:2016-03-01 22:16:08

标签: c# nunit

我试图用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吗?

1 个答案:

答案 0 :(得分:6)

您无需调用cleanup方法,它将自动调用,您需要做的是将一些属性放在TestContextclass中的字段中。< / p>

例如:

使用字段:

[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);
        }
    }   
}