I'm using MSTest, when I first run all of my unit tests (or tests on their own) i want to create a unique identifier that I can put into db records to track the test. Problem is I want the same unique reference to be created and used across all tests. What I really want to use is a DateTime stamp. I'm looking for an event that always gets raised and then I can put it in a static container for the duration of the tests and then just access this static container from within the tests... Is this possible?....
How can I use a single variables to track all of my tests
76 views Asked by Exitos At
2
There are 2 answers
0
On
You could go down the route of having a separate class responsible for holding a static DateTime:
public static class TestIdGenerator
{
private static readonly Lazy<DateTime> _testId = new Lazy<DateTime>(() => DateTime.Now);
public static DateTime TestId
{
get { return _testId.Value; }
}
}
in your test, you access it with
var testId = TestIdGenerator.TestId;
The DateTime will be set the first time the TestId property is accessed, and will remain the same on each subsequent access until the CLR is unloaded - which will happen when all the tests in a particular test run have completed.
I've just tested this, and it does remain constant for all the tests in the fixture, but is then different on the next test run.
You could use the AssemblyInitialize attribute on a method to ensure it runs before any other methods in your test assembly. In that method you could generate your unique ID and set it to a static variable. If your testing methods span assemblies this won't work though.