0

I have to find info about the currently running UnitTest from a helper class' static method. The Idea is getting a unique key from each test.

I thought about using TestContext, not sure if it is possible.

Exemple

[TestClass]
public void MyTestClass
{
    public TestContext TestContext { get; set; }

    [TestMethod]
    public void MyTestMethod()
    {
        TestContext.Properties.Add("MyKey", Guid.NewGuid());

        //Continue....
    }
}


public static class Foo
{

    public static Something GetSomething()
    {
        //Get the guid from test context.
        //Return something base on this key
    }

}

We are currently storing this key on the thread with Thread.SetData, but it is problematic if the tested code spawn multiple thread. For each thread I need to get the same key for a given unit test.

Foo.GetSomething() is not called from the unittest itself. The code calling it is a mock injected by Unity.

Edit

I'll explain the context a little bit, because it seems to be confusing.

The object created via unity is entity framework's context. When running unit tests, the context get its data in a structure that is created by Foo.GetSomething. Let's call it DataPersistance.

DataPersistance cannot be a singleton, because unit tests would impact each others.

We currently have one instance of DataPersistance per thread, witch is nice as long as the tested code is single threaded.

I want one instance of DataPersistance per unit test. If a could get an unique guid per test, I could resolve the instance for this test.

Johnny5
  • 6,664
  • 3
  • 45
  • 78

1 Answers1

0
public static class Foo
{   
    public static Something GetSomething(Guid guid)
    {
        //Return something base on this key
        return new Something();
    } 
}

Test:

[TestClass]
public void MyTestClass
{
    public TestContext TestContext { get; set; }

    [TestMethod]
    public void MyTestMethod()
    {
        Guid guid = ...;
        Something something = Foo.GetSomething(guid);
    }
}
Sam Leach
  • 12,746
  • 9
  • 45
  • 73