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);
}
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?
Thanks :-)
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.
My question is Why do you need this information in unit tests?
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With