如何将DbContext添加到MSTest项目?

时间:2019-01-14 03:31:33

标签: c# mstest dbcontext

我试图测试一些使用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")));

3 个答案:

答案 0 :(得分:3)

我建议使用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...
    }
}

答案 1 :(得分:1)

您从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连接。有关更多详细信息,请参见this document

答案 2 :(得分:0)

您要做的是:

1)在测试项目中添加对上下文项目的引用(如果尚未添加)

2)在测试项目中添加对Entity Framework的引用

3)将appconfig添加到测试项目中,并在其上设置实体框架配置。您的测试将从其自己的配置而非应用程序的配置中读取配置。例如,在运行时,在测试和sqlserver中使用dblocal和codefirst可以非常有用:)

您已经完成了一些操作,我认为您缺少的是第三点:)

相关问题