我正在尝试使用内存数据库来测试我的efcore项目和followed this article。
以下是我的设置:
public class Student
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class StudentContext : DbContext
{
public StudentContext(){
}
public StudentContext(DbContextOptions options)
: base(options)
{
}
public DbSet<Student> Student { get; set; }
}
[TestClass]
public class StudentTest
{
private StudentContext _dbContext;
[TestInitialize]
public void Setup()
{
var optionBuilder = new DbContextOptionsBuilder<StudentContext>();
var options = optionBuilder.UseInMemoryDatabase().Options;
_dbContext = new StudentContext (options);
_dbContext.Users.Add(new Student
{
Id = 1,
FirstName = "tester",
LastName = "tester",
});
_dbContext.SaveChanges();
}
[TestMethod]
public void ValidateStudent()
{
var service = new StudentService(_dbContext);
var response = service.AddStudent(new Student{
Id = 2,
FirstName = "tester2",
LastName = "tester2",
});
Assert.IsTrue(response);
}
[TestCleanup]
public void Cleanup()
{
_dbContext.Database.EnsureDeleted();
_dbContext = null;
}
}
它在以下行抛出System.NullReferenceException:
var optionBuilder = new DbContextOptionsBuilder<StudentContext>();
它在stacktrace中显示的唯一原因如下:
threw exception. System.NullReferenceException: System.NullReferenceException: Object reference not set to an instance of an object..
at StudentContext.OnConfiguring(DbContextOptionsBuilder optionsBuilder)
at Microsoft.EntityFrameworkCore.DbContext.InitializeServices()
at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
at Microsoft.EntityFrameworkCore.DbContext.get_StateManager()
at Microsoft.EntityFrameworkCore.DbContext.EntryWithoutDetectChanges[TEntity](TEntity entity)
at Microsoft.EntityFrameworkCore.DbContext.SetEntityState[TEntity](TEntity entity, EntityState entityState)
at Microsoft.EntityFrameworkCore.DbContext.Add[TEntity](TEntity entity)
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.Add(TEntity entity)
我无法找到此错误的原因。