I have an ASP.NET Core project using .NET Framework 4.6.1 and EF6. Now I want to write some unit tests and already spent hours to configure an in-memory SQLite database for using EF6. But it doesn't work.
So, the question is how can I test my project using EF6 without any mocks (rather an in-memory database)?
My current code:
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());
}
}
If I try to add a user, I get following error:
System.Data.SQLite.SQLiteException: SQL logic error or missing database no such table: Users.
I assume that my tables are generated by calling this.Context.Database.CreateIfNotExists();
, or am I mistaken about that?