Deployment directory change in MSTest v3

June 9th 2023 .NET Unit Testing

When I updated MSTest from v2 to v3 in one of my projects, some tests started failing. It was because of a breaking change in MS Test V3 that caused the TestContext.DeploymentDirectory property to return a different path.

Assertions in my tests were using JSON files copied to output directory. I was depending on the TestContext.DeploymentDirectory property to get its path:

var path = Path.Combine(this.TestContext.DeploymentDirectory, "sample.json");

In MSTest V2, this property returned the \bin\Debug\net7.0 subfolder in the project directory, i.e., the build output folder where the JSON files were copied to.

After the update to MSTest V3, the same property returned a subfolder inside the solution's TestResults folder. There were no JSON files copied there and that's why the tests have started failing.

With that change. None of the TestContext properties returned the build output folder where the JSON files were, so I decided to use the location of the executing assembly to get the right path:

var path = Path.Combine(
    Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? "",
    "sample.json");

This approach doesn't depend on the test framework implementation, so it will keep working even if that changes or with a different test framework.

You can find a sample project showcasing the changes in my GitHub repository. In the last commit, I'm already using MSTest v3. In the previous commit, I'm still using MSTest v2.

Breaking changes are expected between major versions of a library, so it's a good idea to check the documentation before doing the upgrade. In my case, the change only broke the tests, which I detected the first time I ran them. If it was a library that I was using in application code and I didn't have tests for that, I could introduce a bug in the application, and it could take me a while to notice it.

Get notified when a new blog post is published (usually every Friday):

If you're looking for online one-on-one mentorship on a related topic, you can find me on Codementor.
If you need a team of experienced software engineers to help you with a project, contact us at Razum.
Copyright
Creative Commons License