Search code examples
c#mstestdbcontext

How do I add a DbContext to an MSTest project?


I trying to test some code that uses Entity Framework, but I can't figure out how to reference the EF Context classes from the separate MSTest project. Both projects are in the same solution.

Cannot convert lambda expression to type 'DbContextOptions' because it is not a delegate type

In my Test case:

[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);
        }
    }
}

Excerpt from main project Startup.cs (which works fine):

services.AddDbContext<GreenCardContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("MyConnection")));

Solution

  • I would suggest using InMemoryDatabase. In your test class, use [TestInitialize] to setup your dummy database:

    [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...
        }
    }