代码之家  ›  专栏  ›  技术社区  ›  Rilcon42

如何向MSTEST项目添加dbContext?

  •  0
  • Rilcon42  · 技术社区  · 6 年前

    我试图测试一些使用实体框架的代码,但我无法找出如何从单独的MSTEST项目引用EF上下文类。两个项目都在同一个解决方案中。

    无法将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);
            }
        }
    }
    

    摘自main project startup.cs(很好用):

    services.AddDbContext<GreenCardContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("MyConnection")));
    
    3 回复  |  直到 6 年前
        1
  •  3
  •   aqteifan    6 年前

    我建议使用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...
        }
    }
    
        2
  •  1
  •   devNull    6 年前

    你的密码 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 了解更多详细信息。

        3
  •  0
  •   Jorge Rojas    6 年前

    你要做的是:

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

    2)向测试项目添加对实体框架的引用

    3)向测试项目添加AppConfig,并在其上设置Entity Framework配置。您的测试将从它自己的配置中读取配置,而不是从您的应用程序中读取配置。例如,非常有用,运行时在测试和sqlserver中使用dblocal和codefirst:。

    你做了一些这样的事,我想你错过的第三点是:)