I have a solution in which only one class library project is there which has EF Core functionality. This project is being used only to deal with DB. API project is in different solution. Is there any way to unit test this project as just like unit testing of DB as stand alone instead of from API project.
CodePudding user response:
simple example with XUnit and Moq:
public class ExampleDbContext : DbContext
{
public DbSet<ExampleEntity> ExampleEntities { get; set; }
public ExampleDbContext(DbContextOptions<ExampleDbContext> options) : base(options) { }
}
public class ExampleEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
public interface IExampleRepository
{
void Add(ExampleEntity entity);
Task<ExampleEntity> Get(int id);
}
public class ExampleRepository : IExampleRepository
{
private readonly ExampleDbContext _context;
public ExampleRepository(ExampleDbContext context)
{
_context = context;
}
public void Add(ExampleEntity entity)
{
_context.ExampleEntities.Add(entity);
_context.SaveChanges();
}
public Task<ExampleEntity> Get(int id)
{
return _context.ExampleEntities.FindAsync(id);
}
}
public class ExampleRepositoryTests
{
[Fact]
public async Task TestGetMethod()
{
// Arrange
var options = new DbContextOptionsBuilder<ExampleDbContext>()
.UseInMemoryDatabase(databaseName: "TestDB")
.Options;
// Insert seed data into the database using one instance of the context
using (var context = new ExampleDbContext(options))
{
context.ExampleEntities.Add(new ExampleEntity { Id = 1, Name = "Test Entity 1" });
context.SaveChanges();
}
// Use a clean instance of the context to run the test
using (var context = new ExampleDbContext(options))
{
var repository = new ExampleRepository(context);
// Act
var result = await repository.Get(1);
// Assert
Assert.Equal("Test Entity 1", result.Name);
}
}
[Fact]
public void TestAddMethod()
{
// Arrange
var options = new DbContextOptionsBuilder<ExampleDbContext>()
.UseInMemoryDatabase(databaseName: "TestDB")
.Options;
var mockContext = new Mock<ExampleDbContext>(options);
var repository = new ExampleRepository(mockContext.Object);
var entity = new ExampleEntity { Id = 2, Name = "Test Entity 2" };
// Act
repository.Add(entity);
// Assert
mockContext.Verify(c => c.ExampleEntities.Add(entity), Times.Once());
mockContext.Verify(c => c.SaveChanges(), Times.Once());
}
}