简体   繁体   中英

How can I mock a DbContext to use within unit tests of a repository?

I have a repository that contains a public method which I want to write tests around. However to instantiate the repository I need to provide it with a DbContext object.

Trying to mock this DbContext is proving to be difficult as I keep getting back

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
 ---> System.ArgumentNullException: Value cannot be null. (Parameter 'databaseFacade')
   at Microsoft.EntityFrameworkCore.Utilities.Check.NotNull[T](T value, String parameterName)
   at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.GetRelationalService[TService](IInfrastructure`1 databaseFacade)
   at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.SetCommandTimeout(DatabaseFacade databaseFacade, Nullable`1 timeout)
   at sw.cldflt.policymanager.api.UserDbContext..ctor(DbContextOptions`1 options) in C:\source\sw-cldflt-azr-policymanagement\sw-cldflt-policymanagement-api\sw.cldflt.policymanager.api\UserDbContext.cs:line 11
   at Castle.Proxies.UserDbContextProxy..ctor(IInterceptor[] , DbContextOptions`1 options)
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture)
   at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
   at System.Activator.CreateInstance(Type type, Object[] args)
   at Castle.DynamicProxy.ProxyGenerator.CreateClassProxyInstance(Type proxyType, List`1 proxyArguments, Type classToProxy, Object[] constructorArguments)
   at Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, Object[] constructorArguments, IInterceptor[] interceptors)
   at Moq.CastleProxyFactory.CreateProxy(Type mockType, IInterceptor interceptor, Type[] interfaces, Object[] arguments)
   at Moq.Mock`1.InitializeInstance()
   at Moq.Mock`1.OnGetObject()
   at Moq.Mock.get_Object()
   at Moq.Mock`1.get_Object()

I'm trying to write a setup method that instantiates the repo for me to use within the test methods, the setup method is below.

[TestInitialize]
    public void Setup()
    {
        // DbContextOptions options = new DbContextOptions();
        var options = new DbContextOptionsBuilder<UserDbContext>()
            .UseInMemoryDatabase(databaseName: "Test")
            .Options;
        _userDataRepository = new UserDataRepository(_userDbContext);    

    }

What do I need to do to enable me to instiate this repo?

public UserDataRepository(UserDbContext dbContext)
        {
            _dbContext = dbContext;
        }


public class UserDbContext : DbContext
    {
        public UserDbContext(DbContextOptions<UserDbContext> options) : base(options)
        {
            Database.SetCommandTimeout((int)TimeSpan.FromMinutes(3).TotalSeconds);
        }
        public DbSet<User> Users { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>().ToTable("Users").HasKey(e => e.Id);
            base.OnModelCreating(modelBuilder);
        }
    }

Entity Framework Core provides and InMemory datastore for this purpose. You need to add a reference to Microsoft.EntityFrameworkCore.InMemory to your unit test project and then configure it to use the InMemoryProvider. See this link on the official site: https://entityframeworkcore.com/providers-inmemory .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM