Write Unit Test with XUnit, NSubstitute and fakeDb in .net core
For good code and achieve code quality, unit test cases are crucial in any of the development technology these days. Below is the standard…
Write Unit Test with XUnit, NSubstitute and fakeDb in .net core
For good code and achieve code quality, unit test cases are crucial in any of the development technology these days. Below is the standard example of unit test using xuint nuget library and data mocking.
using Xunit;
using NSubstitute;
using FakeDb;
public class ProductServiceTests
{
[Fact]
public void GetProductById_ShouldReturnProduct()
{
// Arrange
var productId = 1;
// Create a fake database instance
var fakeDb = new FakeDatabase();
// Create a mock repository using NSubstitute
var productRepository = Substitute.For<IProductRepository>();
// Set up a fake product for testing
var fakeProduct = new Product
{
Id = productId,
Name = "Test Product",
Price = 19.99
};
// Configure the mock repository to return the fake product when GetById is called
productRepository.GetById(productId).Returns(fakeProduct);
// Create an instance of the class under test, injecting the fake repository
var productService = new ProductService(productRepository);
// Act
var result = productService.GetProductById(productId);
// Assert
// Check that the result is not null
Assert.NotNull(result);
// Check that the returned product has the expected properties
Assert.Equal(productId, result.Id);
Assert.Equal("Test Product", result.Name);
Assert.Equal(19.99, result.Price, 2); // Using 2 as the precision for double comparison
}
}
In this example:
ProductServiceis a hypothetical class that interacts with aProductRepositoryto retrieve products.IProductRepositoryis an interface representing the repository for managing products.FakeDbis a fictitious library for simulating a database. In a real-world scenario, you might use an in-memory database or another approach for testing.
This test case uses NSubstitute to create a mock repository and FakeDb to simulate the database. The test method, GetProductById_ShouldReturnProduct, sets up the necessary dependencies, performs an action (calling the GetProductById method), and then asserts the expected outcome.
Make sure to install the necessary NuGet packages for xUnit, NSubstitute, and FakeDb in your test project. You can install them using the following commands:
dotnet add package xunit
dotnet add package xunit.runner.visualstudio
dotnet add package NSubstitute
dotnet add package FakeDb 메타데이터
- post_id
- 4a7eec0034e2
- slug
- write-unit-test-with-xunit-nsubstitute-and-fakedb-in-net-core-4a7eec0034e2
- url
- https://medium.com/@neer.s/write-unit-test-with-xunit-nsubstitute-and-fakedb-in-net-core-4a7eec0034e2
- canonical_url
- https://medium.com/@neer.s/write-unit-test-with-xunit-nsubstitute-and-fakedb-in-net-core-4a7eec0034e2
- author_url
- https://medium.com/@neer.s
- status
- ok
- fetched_at
- 2026-07-14 13:18:53