Test Repository in .NET core using In Memory database
Tags: dotnet, repository, unittest, tdd
Published: 2024-05-08 19:20:31

## <u>Introduction</u>
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.

## <u>Prerequisites</u>

<u>Packages</u>:

We need the following packages for our `InMemory` database.
![Nuget Packages](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2tztrnujiffe0ohx5vfo.png)

<u>We need to install:</u>
`Microsoft.EntityFrameworkCore.InMemory` (8.0.4), `Microsoft.Extensions.Configuration`(8.0.0) for .NET8 project.

<u>Note:</u> 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:

```C#
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();
   }
}

```

You can also use this to get rid of `InMemory` database- 
```C#
public void Dispose()
{
    this._context.Dispose();
}
```

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

```C#
[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();
}
```
🎉🎉🎉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](https://github.com/extinctsion)