[英]How do I add a DbContext to an MSTest project?
我试图测试一些使用Entity Framework的代码,但无法弄清楚如何从单独的MSTest项目中引用EF Context类。 两个项目都在同一个解决方案中。
无法将Lambda表达式转换为类型'DbContextOptions',因为它不是委托类型
在我的测试案例中:
[TestClass]
public class GreenCardUserTest
{
[TestMethod]
public void TestAddUser()
{
// REFERENCE TO OTHER PROJECT. WORKS FINE
AppUserViewModel a = new AppUserViewModel();
//LIKELY INCORRECT attempt to duplicate code from Startup.cs in other project
using (GreenCardContext _gc = new GreenCardContext(options => options.UseSqlServer(Configuration.GetConnectionString("MyConnection"))))
{
new GCLandingUserModel().AddUser(a,_gc);
}
}
}
主项目Startup.cs的节选(效果很好):
services.AddDbContext<GreenCardContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyConnection")));
我建议使用InMemoryDatabase:
在测试类中,使用[TestInitialize]设置您的虚拟数据库:
[TestClass]
public class GreenCardUserTest
{
private readonly context;
[TestInitialize]
public Setup()
{
DbContextOptions<GreenCardContext> options;
var builder = new DbContextOptionsBuilder<GreenCardContext>();
builder.UseInMemoryDatabase();
var options = builder.Options;
context = new GreenCardContext(options);
}
[TestMethod]
public void TestAddUser()
{
// user context here...
}
}
您从Startup.cs
的代码正在使用委托来告诉您的应用程序如何在运行时构建DbContext。
但是,在测试中,您实际上需要提供一个DbContextOptions
实例,而不仅仅是一个委托。 为此,您可以使用DbContextOptionsBuilder
:
var options = new DbContextOptionsBuilder<GreenCardContext>()
.UseSqlServer(Configuration.GetConnectionString("MyConnection"))
.Options;
using (GreenCardContext _gc = new GreenCardContext(options))
{
new GCLandingUserModel().AddUser(a,_gc);
}
另外,如果您确实坚持对DbConext进行单元测试,则可能需要研究使用InMemoryDatabase,以便在测试中不需要开放的SQL连接。 有关更多详细信息,请参见此文档 。
您要做的是:
1)在测试项目中为上下文的项目添加一个引用(如果还没有的话)
2)将对Entity Framework的引用添加到您的测试项目
3)将一个appconfig添加到您的测试项目中,并在其上设置实体框架配置。 您的测试将从其自己的配置而非应用程序的配置中读取配置。 例如,可以非常有用,例如,在运行时在测试和sqlserver中使用dblocal和codefirst :)
您已经完成了一些操作,我认为您缺少的是第三个:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.