Skip to content

Can no longer mock DbContext in EF 6.3 Preview. #1020

@Pinski

Description

@Pinski

Previously I was able to mock my DbContext for testing purposes using Moq like so:

var mock = new Mock<MyDbContext>();
var service = new MyService(mock.Object);

Ever since upgrading to EF 6.3 Preview 6 now this code throws the following exception

System.ArgumentException
  HResult=0x80070057
  Message=Type to mock must be an interface or an abstract or non-sealed class. 
  Source=Moq
  StackTrace:
   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()
   at Ancestry.Rosetta.UnitTests.Services.CultureServiceTests.InitializeService() in C:\Projects\rosetta-core\Ancestry.Rosetta.UnitTests\Services\TestsOf_CultureService.cs:line 95

Inner Exception 1:
TypeLoadException: Method 'InitializeLazyInternalContext' on type 'Castle.Proxies.RosettaEntitiesProxy' from assembly 'DynamicProxyGenAssembly2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is overriding a method that is not visible from that assembly.

I found an old question on StackOverflow where a similar error was occurring during the upgrade from EF 4.2 to EF 4.3. If I understand the post correctly, InternalsVisibleTo attributes were not being properly stripped out causing Moq to fail:
https://stackoverflow.com/a/9266279/311444

Could something similar to this be happening in EF 6.3?

Steps to reproduce

Trying to instantiate an Object of a mocked DbContext throws an exception.

var mock = new Mock<MyDbContext>();
var service = new MyService(mock.Object);

Further technical details

EF version: 6.3.0-preview6-19304-03
Moq version: 4.12.0
Operating system: Windows 10
IDE: Visual Studio 2017 15.9.13 and Visual Studio 2019 16.2.0 Preview 3.0

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions