Skip to content

Instantly share code, notes, and snippets.

@ctrl-alt-d
Created June 14, 2023 07:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ctrl-alt-d/8bc8d1f9e41a8ea98309397c46933fe4 to your computer and use it in GitHub Desktop.
Save ctrl-alt-d/8bc8d1f9e41a8ea98309397c46933fe4 to your computer and use it in GitHub Desktop.
// this is a way to test Generic Repo that uses EF. Notice, I'm not advocating for generic repos.
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
public static class MyDebug
{
public static List<string> Sql {get; set; } = new();
public static void Capture(string query)
{
if (query.Contains("Execute"))
Sql.Add(query);
}
}
public class Customer
{
public int CustomerId { get; set; }
public string Name { get; set; } = "test data";
}
public class TestDbContext: DbContext
{
public DbSet<Customer> Customers { get; set; } = default!;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseSqlite("Data Source=file:f1?mode=memory&cache=shared")
.LogTo(MyDebug.Capture);
}
}
public class GenericRepository
{
protected readonly DbContext DbContext;
public GenericRepository(DbContext dbContext)
{
DbContext = dbContext;
}
public virtual void Delete<TEntity>(TEntity entity)
where TEntity: class
{
if (DbContext.Entry(entity).State == EntityState.Detached)
{
DbContext.Attach(entity);
}
DbContext.Remove(entity);
}
}
public class CustomerRepositoryItegrationTest
{
private readonly TestDbContext db;
private readonly Customer customer;
public CustomerRepositoryItegrationTest()
{
db = new TestDbContext();
db.Database.EnsureCreated();
customer = new Customer();
db.Customers.Add(customer);
var n = db.SaveChanges();
Assert.Equal(1, n);
}
[Fact]
public void Delete_Attached_Entity()
{
// Arrange
var repo = new GenericRepository(db);
// Act
repo.Delete(customer);
db.SaveChanges();
// Assert
MyDebug.Sql.Last().Should().Contain("DELETE") ;
db.Customers.Any(c => c.CustomerId == customer.CustomerId).Should().BeFalse();
}
[Fact]
public void Delete_Dettached_Entity()
{
// Arrange
var repo = new GenericRepository(db);
db.Entry(customer).State = EntityState.Detached;
// Act
repo.Delete(customer);
db.SaveChanges();
// Assert
MyDebug.Sql.Last().Should().Contain("DELETE") ;
db.Customers.Any(c => c.CustomerId == customer.CustomerId).Should().BeFalse();
}
}
@tzarot
Copy link

tzarot commented Jun 15, 2023

@ctrl-alt-d Thank you for your thorough answer and the time you spent to write it. You really helped me to confirm some concepts, and ideas.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment