cloud, codes, AI

14 September 2026

Creating database unit test with GitHub Copilot

Step-by-Step Guide

  • Set Up Your Environment:

    Ensure you have Visual Studio installed.
  • Install the necessary NuGet packages: Moq and xUnit.
  • Create Your Database Mock:

  • Use Moq to create a mock database context.
  • Write Your Unit Test: Define

     your test cases using the xUnit framework.
  • Use the mock objects to simulate database interactions.

Example

  • Let’s say you have a function GetUserById that retrieves a user from the database by their ID.
 // UserService.cs
using System.Linq;
using Microsoft.EntityFrameworkCore;
public class UserService
{
    private readonly DbContext _context;
    public UserService(DbContext context)
    {
        _context = context;
    }
    public User GetUserById(int userId)
    {
        return _context.Set().FirstOrDefault(u => u.Id == userId);
    }
}
  • Now, let’s create a unit test for this function using a mock database.
// UserServiceTests.cs
using System.Collections.Generic;
using System.Linq;
using Moq;
using Xunit;
using Microsoft.EntityFrameworkCore;
public class UserServiceTests
{
    [Fact]
    public void GetUserById_ReturnsUser()
    {
        // Arrange
        var mockSet = new Mock>();
        var mockContext = new Mock();
        var user = new User { Id = 1, Name = "John Doe" };
        var data = new List { user }.AsQueryable();
        mockSet.As>().Setup(m => m.Provider).Returns(data.Provider);
        mockSet.As>().Setup(m => m.Expression).Returns(data.Expression);
        mockSet.As>().Setup(m => m.ElementType).Returns(data.ElementType);
        mockSet.As>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
        mockContext.Setup(c => c.Set()).Returns(mockSet.Object);
        var service = new UserService(mockContext.Object);
        // Act
        var result = service.GetUserById(1);
        // Assert
        Assert.Equal(user, result);
    }
}

 

 

Explanation

  • Mocking the Database Context:

    • var mockSet = new Mock<DbSet<User>>(); creates a mock DbSet for the User entity.

    • var mockContext = new Mock<DbContext>(); creates a mock DbContext.

  • Setting Up Mock Behavior:

    • The mockSet is set up to return a predefined list of users when queried.

    • mockContext.Setup(c => c.Set<User>()).Returns(mockSet.Object); ensures that the DbContext returns the mock DbSet.

  • Writing the Test:

    • The GetUserById_ReturnsUser test method arranges the mock objects, acts by calling the GetUserById method, and asserts that the returned user matches the expected user.

Using GitHub Copilot, you can generate similar unit tests by providing clear prompts and leveraging its code suggestions to streamline the process. 


Discussion

Leave a Reply

Discover more from ridilabs

Subscribe now to keep reading and get access to the full archive.

Continue reading