【发布时间】:2018-03-27 23:14:08
【问题描述】:
我有一个使用 .NET Framework 4.6.1 和 EF6 的 ASP.NET Core 项目。 现在我想编写一些单元测试,并且已经花费了数小时来配置内存中的 SQLite 数据库以使用 EF6。但它不起作用。
所以,问题是如何在没有任何模拟(而不是内存数据库)的情况下使用 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 逻辑错误或缺少数据库 没有这样的表:用户。
我假设我的表格是通过调用this.Context.Database.CreateIfNotExists(); 生成的,还是我弄错了?
【问题讨论】:
-
我知道它不能回答你的问题,但你应该考虑github.com/tamasflamich/effort
-
FWIW,内存数据库或否,这不是单元测试;这是一个集成测试。在这方面,您确实应该使用与您的实际站点运行相同的数据库平台,即类似 SQL Server,而不是 SQLite。
-
这些不是单元测试。对于单元测试,您可能希望模拟 db 等依赖项。
标签: c# entity-framework sqlite unit-testing asp.net-core