从NUnit向TestResult.xml文件添加更多信息

时间:2008-09-04 19:45:06

标签: unit-testing nunit

我希望能够在单元测试中添加“消息”,使其实际出现在NUnit生成的TestResult.xml文件中。例如,这是当前生成的:

<results>
    <test-case name="MyNamespace.Tests.MyTest" executed="True" success="True" time="0.203" asserts="4" />
</results>

我希望能够有一个额外的属性(或视情况而定),例如:

<results>
    <test-case name="MyNamespace.Tests.MyTest" executed="True" success="True" time="0.203" asserts="4" message="Tested that some condition was met." />
</results>

这个想法是上面的“消息”会以某种方式在测试方法本身内定义(在我的例子中,在运行时生成)。在某个地方是否有遗产可以做这样的事情?

4 个答案:

答案 0 :(得分:5)

在最近的NUnit版本中,你可以这样做:

Assert.AreEqual(250.00, destination.Balance, "some message here");

其中“此处的某些消息”可以是常量消息,也可以是在运行时生成并存储在字符串变量中的消息。如果断言失败,这些消息将仅出现在输出中。但是,通常,您只需要有关失败测试的信息,因此我建议通过添加每个先前的消息来构建字符串,然后将该字符串变量用作所有断言中的消息。这使您可以从失败的测试中获得所需的所有信息。

答案 1 :(得分:2)

这可能忽略了这一点,但是如何命名测试以便他们指出他们测试的内容 - 那么你甚至可能不需要消息。

如果它被证明是绝对必要的,我认为你需要制作你自己的testrunner(在我的脑海中)从TestCase读取一个额外的属性并将其附加到输出。

答案 2 :(得分:0)

我在运行时看不到任何可用内容,但您可能需要调查一些功能:Description属性和Property属性都将文本添加到XML输出文件。不幸的是,它们都是在编译时定义的。

答案 3 :(得分:0)

您可以使用TestContext轻松写出您想要的任何消息。以下是我的设置方法。

我的每个测试都继承自testbase类。这将删除冗余代码。

[TestFixture]
public class TestBase
{

    public IWebDriver driver;

    //[OneTimeSetUp] and [OneTimeTearDown] go here if needed

    [SetUp]
    public void Setup(){
         driver = Shortcuts.SetDriver("my browser");
    }

    [TearDown]
    public void TearDown()
    {
        driver.Quit();
        Comment("@Result: " + TestContext.CurrentContext.Result.Outcome.ToString());
    }

    public void Comment(string _comment)
    {
        TestContext.Out.WriteLine(_comment);
    }
    public void Error(string _error)
    {
        TestContext.Error.WriteLine(_error);
    }

}

您可以看到底部的两个函数在所述TestContext中写出任何消息或错误。这也适用于可并行化的测试。

然后我可以使用该父类来设置我的测试,然后写入我的控制台。

//Role Management
public class RoleManagementTests : TestBase
{
    [TestCase]
    public void RoleManagement_7777_1()
    {
        Comment("Expected: User has the ability to view all roles in the system.");
        //Test goes here
    }
}

现在,您可以使用NUnit Console Runner在输出(Visual Studio)和TestResult.xml中查看结果。