我有一个使用.NET Framework 4.6.1和EF6的ASP.NET Core项目。 现在我想编写一些单元测试,并已花费数小时来配置内存SQLite数据库以使用EF6。但它不起作用。使用EF6(Entity Framework 6)编写单元测试
所以,问题是我怎样才能测试我的项目使用EF6没有任何嘲笑(而不是内存数据库)?
我当前的代码:
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 logic error or missing database no such table: Users.
我假定我的表是通过调用this.Context.Database.CreateIfNotExists();
产生,或我误解了吗?
我知道它不回答你的问题,但你应该考虑https://github.com/tamasflamich/effort – Jim
FWIW,内存数据库还是不行,这不是单元测试;这是一个*集成测试*。在这方面,你真的应该使用你的实际站点运行的同一个数据库平台,例如像SQL Server,而不是SQLite。 –