Skip to content
  1. Blog
  2. General

Automating NUnit Test Cases with GitHub Copilot Chat

TL;DR: GitHub Copilot Chat writes unit tests for selected C# code when you type /tests and say what to cover. We used it to test a product controller’s create, read, update and delete methods, with and without mocks. Review every reply before you commit it. The same habit applies when you test code that calls our eSignature software development kit (SDK) for .NET (Microsoft’s developer platform).

You have a controller with working methods and no tests. Writing each test by hand means setting up objects, calling the method and checking the result, again and again.

This post records how we asked Copilot Chat, an artificial intelligence (AI) assistant, for those tests on a small product management system. It shows each prompt, the code Copilot returned and the problems we spotted on review.

What does GitHub Copilot Chat do for NUnit test cases?

Copilot Chat is a chat panel inside your code editor that answers questions about your code. Its /tests command generates unit tests for the code you select.

Think of a new team member who drafts tests from your notes. The draft saves typing, but you still read it before it goes into the project.

GitHub’s chat cheat sheet lists /tests as “Generate unit tests for the selected code”. Its guide to generating unit tests adds instructions after the command, such as which cases to cover.

What code did we ask Copilot to test?

We tested a product management system that uses CRUD (create, read, update and delete) operations for product details. The first target was the AddProduct method in ProductController.cs.

The method saves the product when the model is valid and returns a bad request otherwise.

public IActionResult AddProduct([FromBody] ProductDetails productDetails)
{
    if (this.ModelState.IsValid)
    {
        this._productService.Add(productDetails);
        return this.Ok();
    }

    return this.BadRequest();
}

How do you generate a test case for adding a product?

Select the method, open Copilot Chat and type /tests followed by what the test should do. Our prompt asked for a real in-memory database instead of a mock.

  1. Install the GitHub Copilot Chat extension in your editor and sign in.
  2. Select the AddProduct method in ProductController.cs.
  3. Type your prompt in the chat box, starting with /tests.
  4. Copy the reply into your test project, then build and run it.

Copilot Chat prompt: /tests Extract all the properties from the ProductDetails class and assign the value and add the product. Verify the count at the end. Don’t mock the service and use InMemory database for test case.

Copilot returned one test for valid details and one for invalid details. Each test checks the product count in the database afterwards.

[Fact]
public void AddProduct_ValidProductDetails_ReturnsOk()
{
    // Arrange
    var options = new DbContextOptionsBuilder()
        .UseInMemoryDatabase(databaseName: "AddProduct_ValidProductDetails_ReturnsOk")
        .Options;

    using (var context = new ProductContext(options))
    {
        var productService = new ProductService(context);
        var controller = new ProductController(null, productService);
        var productDetails = new ProductDetails
        {
            Id = 1,
            Name = "TestProduct",
            Description = "TestDescription",
            Price = 10.0,
            Stock = 100
        };

        // Act
        var result = controller.AddProduct(productDetails);

        // Assert
        Assert.IsType(result);
        Assert.Equal(1, context.Products.Count());
    }
}
[Fact]
public void AddProduct_InvalidProductDetails_ReturnsBadRequest()
{
    // Arrange
    var options = new DbContextOptionsBuilder()
        .UseInMemoryDatabase(databaseName: "AddProduct_InvalidProductDetails_ReturnsBadRequest")
        .Options;

    using (var context = new ProductContext(options))
    {
        var productService = new ProductService(context);
        var controller = new ProductController(null, productService);
        controller.ModelState.AddModelError("Name", "Required");
        var productDetails = new ProductDetails
        {
            Id = 1,
            Description = "TestDescription",
            Price = 10.0,
            Stock = 100
        };

        // Act
        var result = controller.AddProduct(productDetails);

        // Assert
        Assert.IsType(result);
        Assert.Equal(0, context.Products.Count());
    }
}

How do you ask Copilot for tests with a mocked service?

Say in the prompt that the service should be mocked, and describe what the mock should record. We asked for a mock that counts each product twice, to see whether Copilot would follow an unusual rule.

Copilot Chat prompt: /tests Mock the product service and add the product details and increase the count twice for every entry.

Copilot followed the rule exactly. The mock’s callback adds each product to the list twice, so the valid test expects a count of 2.

[Fact]
public void AddProduct_ValidProductDetails_IncreasesCountTwice()
{
    var productServiceMock = new Mock ();
    var productList = new List();
    productServiceMock.Setup(service => service.Add(It.IsAny())).Callback(product =>
    {
        productList.Add(product);
        productList.Add(product);
    });

    var controller = new ProductController(null, productServiceMock.Object);
    var productDetails = new ProductDetails
    {
        Id = 1,
        Name = "TestProduct",
        Description = "TestDescription",
        Price = 10.0,
        Stock = 100
    };

    var result = controller.AddProduct(productDetails);

    Assert.IsType(result);
    Assert.Equal(2, productList.Count);
}
[Fact]
public void AddProduct_InvalidProductDetails_DoesNotIncreaseCount()
{
    var productServiceMock = new Mock();
    var productList = new List();

    var controller = new ProductController(null, productServiceMock.Object);
    controller.ModelState.AddModelError("Name", "Required");
    var productDetails = new ProductDetails
    {
        Id = 1,
        Description = "TestDescription",
        Price = 10.0,
        Stock = 100
    };

    var result = controller.AddProduct(productDetails);

    Assert.IsType(result);
    Assert.Equal(0, productList.Count);
}

A test like this proves only what the prompt asked for. Your real service adds a product once, so drop the doubled count before you keep the test.

How do you generate model validation tests with Copilot?

Ask Copilot to validate the properties of your model class. Our prompt was short, and Copilot wrote one test per validation rule.

Copilot Chat prompt: /tests Do model validation for all applicable properties

The tests cover a missing name, a name over 50 characters and a quantity out of range. Each one adds the error to the model state by hand with AddModelError.

[Fact]
public void AddProduct_MissingRequiredName_ReturnsBadRequest()
{
    var productServiceMock = new Mock();
    var productList = new List();

    var controller = new ProductController(null, productServiceMock.Object);
    controller.ModelState.AddModelError("Name", "Required");
    var productDetails = new ProductDetails
    {
        Id = 1,
        Description = "TestDescription",
        Price = 10.0m,
        Quantity = 10,
        Category = "TestCategory",
        Manufacturer = "TestManufacturer",
        DateAdded = DateTime.Now
    };

    var result = controller.AddProduct(productDetails);

    Assert.IsType(result);
    Assert.Empty(productList);
}

[Fact]
public void AddProduct_NameExceedsMaxLength_ReturnsBadRequest()
{
    var productServiceMock = new Mock();
    var productList = new List();

    var controller = new ProductController(null, productServiceMock.Object);
    controller.ModelState.AddModelError("Name", "Name cannot exceed 50 characters.");
    var productDetails = new ProductDetails
    {
        Id = 1,
        Name = new string('A', 51),
        Description = "TestDescription",
        Price = 10.0m,
        Quantity = 10,
        Category = "TestCategory",
        Manufacturer = "TestManufacturer",
        DateAdded = DateTime.Now
    };

    var result = controller.AddProduct(productDetails);

    Assert.IsType(result);
    Assert.Empty(productList);
}
[Fact]
public void AddProduct_QuantityOutOfRange_ReturnsBadRequest()
{
    var productServiceMock = new Mock();
    var productList = new List();

    var controller = new ProductController(null, productServiceMock.Object);
    controller.ModelState.AddModelError("Quantity", "Quantity must be greater than 0 and less than 100.");
    var productDetails = new ProductDetails
    {
        Id = 1,
        Name = "TestProduct",
        Description = "TestDescription",
        Price = 10.0m,
        Quantity = 101,
        Category = "TestCategory",
        Manufacturer = "TestManufacturer",
        DateAdded = DateTime.Now
    };

    var result = controller.AddProduct(productDetails);

    Assert.IsType(result);
    Assert.Empty(productList);
}

How do you switch from AddModelError to TryValidateModel?

Ask Copilot to run the model’s own validation rules instead of adding errors by hand. We sent a follow-up prompt in the same chat.

Copilot Chat prompt: /tests Instead of AddModelError, use TryValidateModel for AddProduct method

The reply calls TryValidateModel on product details that have no name. Notice that it builds the controller with one argument, while the earlier tests passed two.

[Fact]
public void AddProduct_InvalidProductDetails_ReturnsBadRequest()
{
    var productServiceMock = new Mock();
    var productList = new List();

    var controller = new ProductController(productServiceMock.Object);
    var productDetails = new ProductDetails
    {
        Id = 1,
        Description = "TestDescription",
        Price = 10.0m,
        Quantity = 10,
        Category = "TestCategory",
        Manufacturer = "TestManufacturer",
        DateAdded = DateTime.Now
    };

    controller.TryValidateModel(productDetails);

    var result = controller.AddProduct(productDetails);

    Assert.IsType(result);
    Assert.Empty(productList);
}

How do you write test cases for every method in a file?

Open the file, then ask Copilot to cover every method in it. Our prompt asked for both success and failure status codes.

Copilot Chat prompt: /tests write a test case for all the methods considering both success and failure status code.

Copilot returned tests for adding, getting, updating and deleting a product. Each method gets one test that should pass and one that checks the failure path.

[Fact]
public void AddProduct_ValidProductDetails_ReturnsOk()
{
    var productServiceMock = new Mock();
    var productList = new List();
    productServiceMock.Setup(service => service.Add(It.IsAny())).Callback(product =>
    {
        productList.Add(product);
    });

    var controller = new ProductController(null, productServiceMock.Object);
    var productDetails = new ProductDetails
    {
        Id = 1,
        Name = "TestProduct",
        Description = "TestDescription",
        Price = 10.0m,
        Quantity = 10,
        Category = "TestCategory",
        Manufacturer = "TestManufacturer",
        DateAdded = DateTime.Now
    };

    var result = controller.AddProduct(productDetails);

    Assert.IsType(result);
    Assert.Single(productList);
}

[Fact]
public void AddProduct_InvalidProductDetails_ReturnsBadRequest()
{
    var productServiceMock = new Mock();
    var productList = new List();

    var controller = new ProductController(null, productServiceMock.Object);
    controller.ModelState.AddModelError("Name", "Required");
    var productDetails = new ProductDetails
    {
        Id = 1,
        Description = "TestDescription",
        Price = 10.0m,
        Quantity = 10,
        Category = "TestCategory",
        Manufacturer = "TestManufacturer",
        DateAdded = DateTime.Now
    };

    var result = controller.AddProduct(productDetails);

    Assert.IsType(result);
    Assert.Empty(productList);
}

[Fact]
public void GetProduct_ExistingProduct_ReturnsProductDetails()
{
    var productServiceMock = new Mock();
    var productDetails = new ProductDetails
    {
        Id = 1,
        Name = "TestProduct",
        Description = "TestDescription",
        Price = 10.0m,
        Quantity = 10,
        Category = "TestCategory",
        Manufacturer = "TestManufacturer",
        DateAdded = DateTime.Now
    };
    productServiceMock.Setup(service => service.Get("TestProduct")).Returns(productDetails);

    var controller = new ProductController(null, productServiceMock.Object);

    var result = controller.GetProduct("TestProduct");

    Assert.Equal(productDetails, result);
}

[Fact]
public void GetProduct_NonExistingProduct_ReturnsNull()
{
    var productServiceMock = new Mock();
    productServiceMock.Setup(service => service.Get("NonExistingProduct")).Returns((ProductDetails)null);

    var controller = new ProductController(null, productServiceMock.Object);

    var result = controller.GetProduct("NonExistingProduct");

    Assert.Null(result);
}

[Fact]
public void UpdateProduct_ValidProductDetails_ReturnsOk()
{
    var productServiceMock = new Mock();
    var productDetails = new ProductDetails
    {
        Id = 1,
        Name = "TestProduct",
        Description = "TestDescription",
        Price = 10.0m,
        Quantity = 10,
        Category = "TestCategory",
        Manufacturer = "TestManufacturer",
        DateAdded = DateTime.Now
    };

    var controller = new ProductController(null, productServiceMock.Object);

    var result = controller.UpdateProduct(productDetails);

    Assert.IsType(result);
}

[Fact]
public void UpdateProduct_InvalidProductDetails_ReturnsBadRequest()
{
    var productServiceMock = new Mock();

    var controller = new ProductController(null, productServiceMock.Object);
    controller.ModelState.AddModelError("Name", "Required");
    var productDetails = new ProductDetails
    {
        Id = 1,
        Description = "TestDescription",
        Price = 10.0m,
        Quantity = 10,
        Category = "TestCategory",
        Manufacturer = "TestManufacturer",
        DateAdded = DateTime.Now
    };

    var result = controller.UpdateProduct(productDetails);

    Assert.IsType(result);
}

[Fact]
public void DeleteProduct_ExistingProduct_ReturnsOk()
{
    var productServiceMock = new Mock();
    productServiceMock.Setup(service => service.Remove("TestProduct"));

    var controller = new ProductController(null, productServiceMock.Object);

    var result = controller.DeleteProduct("TestProduct");

    Assert.IsType(result);
}

[Fact]
public void DeleteProduct_NonExistingProduct_ReturnsOk()
{
    var productServiceMock = new Mock();
    productServiceMock.Setup(service => service.Remove("NonExistingProduct"));

    var controller = new ProductController(null, productServiceMock.Object);

    var result = controller.DeleteProduct("NonExistingProduct");

    Assert.IsType(result);
}

Why did Copilot write xUnit tests instead of NUnit?

Our prompts named no test framework, and every reply used xUnit syntax. The [Fact] attribute comes from xUnit, while NUnit marks a test with the Test attribute.

NUnit checks results with Assert.That and constraints, such as Assert.That(result, Is.EqualTo(1)). Start your prompt with /tests Write NUnit tests when your project uses NUnit. You can also ask Copilot to rewrite an existing reply for NUnit.

What should you check before you commit Copilot’s tests?

Build and run every test, then read each assertion against what your code should do. The replies above show four things worth checking.

  • The test framework matches your project, as the xUnit replies show.
  • The model fields match your class: replies used both Stock and Quantity.
  • The constructor arguments match your controller, which changed between replies.
  • Each assertion checks real behavior, not only the rule from your prompt.

GitHub’s guide notes that Copilot may first offer to configure unit tests for your project. Decide that once, so later replies stay consistent.

Where do you go next with AI-written tests?

Copilot drafts the tests, and you keep the ones that prove your code works. Pick the next step that fits your project.

Frequently asked questions

Can GitHub Copilot Chat write NUnit tests?

Yes. Ask for NUnit by name in your prompt, then check that the reply uses the [Test] attribute and Assert.That. Without that, the reply may use another framework, as ours did.

What does the /tests command do in Copilot Chat?

It asks Copilot to generate unit tests for the code you have selected. You add plain instructions after it, such as which cases to cover.

Do I need to select code before I use /tests?

Selecting the method gives Copilot the exact code to test. For a whole file, open the file and ask for tests for every method in it.

Can Copilot write tests that mock a service?

Yes. Say in the prompt that the service should be mocked. Our reply used a mock object with a callback that recorded each product added.

Should I trust tests that Copilot writes?

Treat them as a first draft. Build them, run them and read each assertion, because a test can pass while it checks the wrong thing.

Why did my Copilot tests come back with [Fact] instead of [Test]?

The [Fact] attribute comes from xUnit, and [Test] comes from NUnit. Name the framework you use in the prompt and ask Copilot to rewrite the tests.

Can Copilot write model validation tests in C#?

Yes. We asked it to validate every applicable property of our model class, and it wrote tests for a missing name, a long name and an out-of-range quantity.

Does Copilot Chat replace writing tests by hand?

It saves much of the typing, but you still decide what each test should prove. Then you fix the parts that differ from your code.

Senthil Kumar

Senthil Kumar M, who works for Syncfusion as a Product Manager. He has been actively involved in web development since 2012 and has a passion for both front-end and back-end technologies.

More posts by Senthil Kumar
Get started

Sign up for your free trial today!

Start free trial
  • 30-day free trial
  • No credit card required