我有一个使用.NET Framework 4.6.1和EF6的ASP.NET Core项目。
现在我想编写一些单元测试,并已经花费了几个小时来配置一个内存中的SQLite数据库以使用EF6。但是它不起作用。
所以问题是如何在没有任何mock的情况下(而是使用内存中的数据库)测试我的项目?
我的当前代码:
public class DataAccessLayer : DbContext
{
public DataAccessLayer(string connectionString)
: base(connectionString) {
}
public DataAccessLayer(DbConnection connection)
: base(connection, true) {
}
public DbSet<User> Users { get; set; }
public DbSet<Setting> Settings { get; set; }
public DbSet<UserRole> UserRoles { get; set; }
public DbSet<MainKey> MainKeys { get; set; }
}
[Table("Users")]
public class User
{
[Key]
[Required]
public int UserID { get; set; }
[Required][StringLength(50)]
public string UserName { get; set; }
...
}
public class Testbase
{
protected DataAccessLayer Context { get; private set; }
[TestInitialize]
public virtual void SetUp()
{
var connection = this.CreateConnection();
connection.Open();
this.Context = new DataAccessLayer(connection);
this.Context.Database.CreateIfNotExists();
}
private SQLiteConnection CreateConnection() {
var connectionStringBuilder = new SQLiteConnectionStringBuilder { DataSource = ":memory:" };
return new SQLiteConnection(connectionStringBuilder.ToString());
}
}
如果我试图添加一个用户,就会出现以下错误:
我认为我的表是通过调用System.Data.SQLite.SQLiteException: SQL逻辑错误或缺失数据库 没有这样的表:Users。
this.Context.Database.CreateIfNotExists();
生成的,或者我对此有误解吗?