Edit

Share via


Generate unit tests with GitHub Copilot

In this article, you explore how to generate unit tests and test projects in C# using the xUnit framework with the help of Visual Studio commands and GitHub Copilot. Using Visual Studio in combination with GitHub Copilot significantly simplifies the process of generating and writing unit tests.

Create a test project

Imagine that there's a ProductService class with a GetProductById method that depends on the IProductDataStorage and ICacheClient interfaces.

public class ProductService(
    IProductDataStorage productDataStorage,
    ICacheClient cacheClient)
{
    public async Task<Product?> GetProductById(int productId)
    {
        var product = await cacheClient.GetProduct(productId);

        if (product is not null)
        {
            return product;
        }

        product = await productDataStorage.GetProduct(productId);

        if (product is not null)
        {
            await _cacheClient.SetProduct(product);
        }

        return product;
    }
}

To generate a test project and a stub method, follow these steps:

  • Select the method.
  • Right-click and select Create Unit Tests.

Command Create Unit Tests

In the Create Unit Tests dialog, select xUnit from the Test Framework dropdown menu.

Note

The Create Unit Tests command defaults to the MSTest framework. However, since this example uses xUnit, you need to install the Visual Studio extension xUnit.net.TestGenerator2022.

Create Unit Tests window

  • If you don't have a test project yet, choose New Test Project or select an existing one.
  • If necessary, specify a template for the namespace, class, and method name, then click OK.

After a few seconds, Visual Studio will pull in the necessary packages, and you'll get a generated xUnit project with the required packages and structure, a reference to the project being tested, and the ProductServiceTests class and a stub method.

Generated stub method

Generate the tests themselves

  • Select the method being tested again.

  • Right-click and select Ask Copilot.

  • Enter a simple prompt, such as:

    "Generate unit tests using xunit, nsubstitute and insert the result into #ProductServiceTests file."

    You need to select your test class when you type the # character.

Tip

For quick search, it's desirable that ProductServiceTests is open in a separate tab.

Prompt for generate tests

Execute the prompt, click Accept, and Copilot generates the test code. After that, it remains to install the necessary packages.

When the packages are installed, the tests can be run. This example worked on the first try: Copilot knows how to work with NSubstitute, and all dependencies were defined through interfaces.

Generated tests