如何在UTest类中初始化内存数据库上下文
如何在 UnitTest 类中初始化假内存数据库上下文以使用 CatDbContext 来测试存储库。我收到错误:OneTimeSetUp:找不到合适的构造函数。 我需要如何初始化数据库,以用于测试catRepository。
namespace CatsCRUDAppTest
{
public class CatRepositoryTests
{
private IRepository<Cat> catRepository;
private FakeDbContext context;
private Cat defaultCat = new Cat() {Id = 0, Name = "name" };
// OneTimeSetUp: No suitable constructor was found
public CatRepositoryTests(FakeDbContext fake)
{
catRepository = new CatRepository(fake);
context = fake;
}
//
[Test]
public void CreateTrueTest()
{
Cat cat = defaultCat;
catRepository.Create(cat);
context.SaveChanges();
Cat existingCat = context.Find<Cat>(cat.Id);
Assert.IsNotNull(existingCat);
}
}
存储库类: 该类获取 CatDbContext 进行初始化。
namespace DAL.Repositories
{
public class CatRepository : IRepository<Cat>
{
private CatDbContext db;
public CatRepository(CatDbContext context)
{
db = context;
}
public async void Create(Cat item)
{
await db.Cats.AddAsync(item);
}
假数据库上下文:
public class FakeDbContext : CatDbContext
{
public FakeDbContext(DbContextOptions<CatDbContext> options) : base(options)
{
}
public DbSet<Cat> Cats { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseInMemoryDatabase(databaseName: "FakePersonalSiteDbContext");
}
}
How to initialize fake inmemory database context in UnitTest class for testing repository, which using CatDbContext. I got Error: OneTimeSetUp: No suitable constructor was found.
How i need ti initialize database, to use for testing catRepository.
namespace CatsCRUDAppTest
{
public class CatRepositoryTests
{
private IRepository<Cat> catRepository;
private FakeDbContext context;
private Cat defaultCat = new Cat() {Id = 0, Name = "name" };
// OneTimeSetUp: No suitable constructor was found
public CatRepositoryTests(FakeDbContext fake)
{
catRepository = new CatRepository(fake);
context = fake;
}
//
[Test]
public void CreateTrueTest()
{
Cat cat = defaultCat;
catRepository.Create(cat);
context.SaveChanges();
Cat existingCat = context.Find<Cat>(cat.Id);
Assert.IsNotNull(existingCat);
}
}
Repository class:
That class get CatDbContext to initialize.
namespace DAL.Repositories
{
public class CatRepository : IRepository<Cat>
{
private CatDbContext db;
public CatRepository(CatDbContext context)
{
db = context;
}
public async void Create(Cat item)
{
await db.Cats.AddAsync(item);
}
FakeDbContext:
public class FakeDbContext : CatDbContext
{
public FakeDbContext(DbContextOptions<CatDbContext> options) : base(options)
{
}
public DbSet<Cat> Cats { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseInMemoryDatabase(databaseName: "FakePersonalSiteDbContext");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
需要使用dbBuilder。
Need to use dbBuilder.