从 NUnit TestContext 检索测试持续时间 [英] Retrieving test duration from NUnit TestContext

查看:63
本文介绍了从 NUnit TestContext 检索测试持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在我的测试代码中访问测试的持续时间.我一直在查看 NUnit 中的 TestContext 类,但是当我找到关于FullName"的信息时,我不知道从哪里访问测试的持续时间.

I would like to be able to access the duration of a test in my test code. I have been looking at the TestContext class in NUnit, but while I find information abut "FullName", I cannot figure out where to access the duration of a test.

[TearDown]
public void TearDown()
{
    Console.WriteLine(TestContext.CurrentContext.Test.FullName); 
}

除了测试的全名之外,我还可以访问 Properties 字典,但在所有情况下,只有值是_CATEGORIES"条目.

Apart from the full name of the test, I can access a Properties dictionary, but in all cases, only value is a "_CATEGORIES" entry.

我如何完成我想做的事?

How do I accomplish what I want to do?

谢谢:-)

推荐答案

无法从 NUnit TestContext 获取此信息,因为 NUnit 不提供此类信息.基本上,单元测试应该很快并告诉您某些部分是否损坏,但不要将它们用作时间注册系统.

It is not possible to get this information from NUnit TestContext because NUnit doesn't provide such information there. Basically, unit tests should be fast and tell you if some parts are broken, but don't use them as a time registration system.

我的问题是为什么在单元测试中需要这些信息?

NUnit 提供用于定义测试时间限制的属性:超时<代码>最大时间.如果测试用例运行的时间比指定的时间长,则这两个属性都将用于告知此失败.如果定义了Timeout 属性,测试将尽快中断.如果定义了 MaxTime 属性,则不会中断测试用例.

NUnit provides attributes to define time limits for tests: Timeout and MaxTime. If the test case runs longer than the time specified, both attributes will be used to tell about this failure. If the Timeout attribute is defined, the test will be interrupted as soon as possible. If the MaxTime attribute is defined the test case will not be interrupted.

您还可以检查带有测试结果的文件 TestResult.xml 并找到表示执行时间的属性(称为time).如果您的老板想要一些好看的东西,可以使用特殊工具 nunit-results 生成 HTML 报告.

You could also check a file with test results TestResult.xml and find an attribute which represents execution time (it's called time). If your boss wants something good-looking, HTML report can be generated using a special tool nunit-results.

您还想知道代码中的执行时间吗?从这个类继承你的测试:

Do you still want to know execution time in the code? Inherit your test from this class:

[TestFixture]
public abstract class BaseTestClass
{
    private Stopwatch _stopWatch;

    [SetUp]
    public void Init()
    {
        _stopWatch = Stopwatch.StartNew();   
    }

    [TearDown]
    public void Cleanup()
    {
        _stopWatch.Stop();
        Debug.WriteLine("Excution time for {0} - {1} ms",
            TestContext.CurrentContext.Test.Name,
            _stopWatch.ElapsedMilliseconds);
        // ... add your code here
    }
}

这篇关于从 NUnit TestContext 检索测试持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆