DEV Community

Cover image for Test Repository in .NET core using In Memory database
Aditya Sharma
Aditya Sharma

Posted on

Test Repository in .NET core using In Memory database

Introduction

In the world of software development, securing the dependability and stability of your code base is critical. One critical component of doing this is the installation of thorough test suites. Among the different components of a software application, repositories play an important role in interfacing with data sources, such as a database, file system, or external API.

In this article, we will look at the nuances of writing test cases specifically for repositories. Whether you're using repositories in a classic relational database or in a modern microservices architecture, creating strong test cases guarantees that your data access layer works properly under a variety of scenarios. Let's discuss how we can use Microsoft's InMemory library to test repository.

Prerequisites

Packages:

We need the following packages for our InMemory database.
Nuget Packages

We need to install:
Microsoft.EntityFrameworkCore.InMemory (8.0.4), Microsoft.Extensions.Configuration(8.0.0) for .NET8 project.

Note: You may install the correct version of packages according to your <TargetFramework>

Once the required packages are installed, we are good to go.
Inside your UnitTest.Repository (assuming you make the repository test folder), setup in the similar way:

using FluentAssertions;

namespace UnitTest.Repository.ShapeTests
{
   public class ShapesRepositoryTests : IDisposable
   {
      private readonly DbContextOptions<ShapesDbContext> _options;
      private readonly ShapesDbContext _context;
   }
    //press ctor to initialise a constructor. 
    //We can setup InMemory database in Constructor or call it from
    //a seperate common class for all repository testing.

    public ShapesRepositoryTests()
   {
    // Arrange: Set up the in-memory database in the constructor
    this._options = new DbContextOptionsBuilder<ShapesDbContext>()
        .UseInMemoryDatabase(databaseName: "ShapesMockDbContext") //We can give any name to the InMemory database.
        .Options;

    this._context = new ShapesDbContext(this._options);
    List<Shapes> shapes = [];

    //We can use any nuget library to generate fake data
    for (int i = 0; i < 1000; i++)
    {
        shapes.Add(ShapesMockData.GenerateFakeShapes()); //Generate fake shapes and add all shapes to the List<Shapes>.
    }

    // Add test data to the in-memory database
    this._context.Users.AddRange(users);

    this._context.UserConfiguration.AddRange(userConfigurations);

    //Saving changes in the InMemory database.
    this._context.SaveChanges();
   }
}

Enter fullscreen mode Exit fullscreen mode

You can also use this to get rid of InMemory database-

public void Dispose()
{
    this._context.Dispose();
}
Enter fullscreen mode Exit fullscreen mode

After setting up your database, you can now write test cases as -

[Fact]
public async Task GetAllShapesShouldNotReturnNull()
{
    //Arrange
    var repository = new ShapesRepository(this._context);

    // Act
    var result = await repository.GetAllShapes(); //Testing method inside the ShapesRepository

    // Assert
    result.Should().NotBeNull();
}
Enter fullscreen mode Exit fullscreen mode

๐ŸŽ‰๐ŸŽ‰๐ŸŽ‰Congratulations! you have successfully setup an InMemory database and tested your repository.

Conclusion

I hope, now you will be able to use InMemory database to test your repository. Happy coding!

Give a like if it helped and follow me for more such content on Github

Top comments (0)