Search code examples
c#asp.net-coremstest

Set System.Diagnostics.Activity.Current in MS Unit Tests (.NET Core)


I have domain classes that reference System.Diagnostics.Activity.Current.Id in my web api. It uses this value as a correlation Id once the object is serialized and stored in Cosmos. I have no issue getting this value when making calls into the API. However if I try to reference this value in my domain unit tests, the System.Diagnostics.Activity.Current is null. I have tried setting it in my unit test functions but it is still always null in my domain.

System.Diagnostics.Activity.Current = new System.Diagnostics.Activity("MyUnitTests");

I know System.Diagnostics.Activity.Current is driven from the current HttpContext but there also is no current http context in my domain unit tests. How can I make this work with my unit tests?

Example: Domain Class

public class Company
{  
    public int CompanyId { get; private set; }        
    public string Name { get; private set; }
    public string CorrelationId { get { return System.Diagnostics.Activity.Current.Id; } }
}

Unit Test

    [TestMethod]
    public void MyTest()
    {
        Company c = new Company();
        Assert.AreNotEqual(string.Empty, c.CorrelationId);
    }

This unit test throws a null reference exception because System.Diagnostics.Activity.Current is null.


Solution

  • This is a design issue around mixing concerns and is a possible code smell.

    Current code is tightly coupled to run time concerns that are not present when unit testing in isolation.

    You'll most likely need to run an integration test where actual requests are made with a valid context.

    Assigning the id via a service abstraction would help loosen the coupling to run time concerns.

    And remove the need to unit unit test a simple domain POCO used to store run time data.