Quick way to create a unit test project in Visual Studio

You don’t need to manually create a unit test project (through the UI or through the command line). Instead, you can can use the Create Unit Tests command in Visual Studio to generate a unit test project, add it to the solution, and wire up a test stub all at once.

Note: This approach can even be used if you’re doing TDD and adding tests first.

1 – Add a dummy public method if necessary

First things first, the project you’re testing needs at least one public method in a public class to be able to use the Create Unit Tests command. If you try to use it on anything else, you’ll get the following popup error:

Create Unit Tests is supported only on a non-test project and within a public class or a public method

If your project doesn’t have any public methods yet, you can simply add a dummy class and method:

public class Class1 { public void Test() { } }
Code language: C# (cs)

The purpose of this is so you can use the Create Unit Tests command. Afterwards, you can delete this dummy code.

If you’re doing pure TDD, and adding tests first, that’s OK. You can add a new project with a dummy class/method so you can get the unit test project wired up.

2 – Use the Create Unit Tests command

  • Right-click a public method (in this example: Class1.Test()) in the project and click Create Unit Tests from the context menu.
  • In the Create Unit Tests window, keep the defaults and click OK.
Visual Studio - Create Unit Tests command window

Note: The defaults are usually good enough for getting started. You can always change things after the project is created, so don’t worry too much about getting the initial settings just right.

This will create the unit test project with a test stub against the public method you used the Create Unit Tests command on.

3 – Run the unit test

Go to the generated test stub (in this case it’s called TestTest), right-click and click Run Test(s):

[TestClass()] public class Class1Tests { [TestMethod()] public void TestTest() { Assert.Fail(); } }
Code language: C# (cs)

If everything is wired up properly, then you should see the unit test fail.

4 – Clean up and start writing the real tests

Now that the test project is wired up and working, you can start writing the real tests.

You can either delete the dummy code (and accompanying test stub), or you can repurpose them and start writing the real tests and code.

I practice TDD, so when I use this approach for initializing the unit test project, I like to repurpose the test stub method by writing the first real test. This allows me to hit the ground running.

Leave a Comment