Question Details

No question body available.

Tags

c# visual-studio unit-testing mstest

Answers (2)

April 13, 2026 Score: 3 Rep: 19,401 Quality: Medium Completeness: 80%

I've run into this for years with end-to-end tests. I haven't found a way to stop the test and perform cleanup. Since you are using MS Test, the [Timeout(int)] attribute might be the only other option.

[TestClass]
public class TimeoutTests
{
    [TestMethod]
    [Timeout(5000)] // 5 seconds
    public void TestWithTimeout()
    {
        // Test must complete within 5 seconds
    }
}

Source: https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-mstest-writing-tests-controlling-execution#timeout-attributes

According to the MSTest lifecycle, you can implement IDisposable. Maybe that will work.

Generally, Microsoft recommends IDisposable over [TestCleanup]. See also MSTEST0021: Prefer Dispose over TestCleanup methods, which is about the IDE warning.

Unfortunately, I couldn't find explicit documentation attesting to whether or not the IDisposable interface is still invoked when you kill a test run, but it's worth an experiment.

April 13, 2026 Score: 3 Rep: 39,496 Quality: Medium Completeness: 50%

My recommendation would be to run a cleanup script before tests rather than trying to ensure that cleanup is always run after a test. There will always situations where cleanup has not been run, like if the computer has an uncontrolled power loss. Or if the tested code is buggy and leaves the database in an unknown state.

Our approach to database tests is to:

  1. Generate a computer unique database name. This allows multiple computers to run tests concurrently using the same database host.
  2. Try to delete any existing database with that name
  3. Create a new database
  4. Run the database initialization script to populate the database to a known initial state
  5. Run the tests
  6. Delete the database in a cleanup method

This ensures that tests do not fail if there is an existing database in a unknown state. It is not perfect, since old databases can persist until the next time a computer runs the tests, and there can still be concurrency issues if you try to run tests concurrently from the same computer, but it has worked well enough for us.

It do require that you have an automated way to create and initialize databases, but that is very useful for other purposes as well. A similar approach should be possible for temporary files or other persistent state, if that is a concern.