I'm using EF7 with In-Memory database and xUnit for repository testing. I'd like to know if it's a good practice initializing the database in this manner for reuse it in every test method, specifically through the Initialize()
method:
private Context _context;
private BrandsRepository _repository;
private void Initialize()
{
var db = new DbContextOptionsBuilder();
db.UseInMemoryDatabase();
_context = new Context(db.Options);
_repository = new BrandsRepository(_context);
_context.Database.EnsureDeleted();
_context.Database.EnsureCreated();
}
[Fact]
public void Retrieve_Brands()
{
// Arrange
Initialize();
var brands = new List<Brand>()
{
new Brand() { Name = "First" },
new Brand() { Name = "Second" },
new Brand() { Name = "Third" }
};
_context.Brands.AddRange(brands);
_context.SaveChanges();
// Act
var retrievedBrands = _repository.GetAll();
// Assert
Assert.Equal(retrievedBrands, brands);
}
[Fact]
public void Add_a_Brand()
{
// Arrange
Initialize();
var brand = new Brand() { Name = "First" };
// Act
_repository.Add(brand);
// Assert
Assert.Equal(_context.Brands.First(), brand );
}