chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
Welcome to Typemock Community! Here you can ask and receive answers from other community members. If you liked or disliked an answer or thread: react with an up- or downvote.
0 votes
Hello there,
I have a question as to how to best mock a DbSet so that it can be acted upon with Linq expressions?

//Arrange
var _entityDbSet = Isolate.Fake.Instance<DbSet<SomeEntityClass>>();

//Arrange?
//_entityDbSet = Isolate.Fake.Instance<DbSet<SomeEntityClass>>(Members.ReturnRecursiveFakes);

//Arrange?
Isolate.WhenCalled(() => _entityDbSet).WillReturnCollectionValuesOf(new List<SomeEntityClass> { new SomeEntityClass() });

//Act
var items = _entityDbSet.Where(e => true);

Either of the above setups causes .Where to throw an exception, in Expression.ValidateOneArgument.
In the method, the mocked expression type (null) is compared to the entity list element type (SomeEntityClass) and
are found to be unequal.


Please explain how to go about mocking dbset.


Best regards,
Christian L
asked by ChristianL2 (3.1k points)

3 Answers

0 votes
Hi Christian,

In order to understand the problem better I need you to post the code you are trying to test and specify exactly what you are trying to fake in it, including its base type and namespace ( Basically what you think might help me to recreate this problem locally).
answered by alex (18k points)
0 votes
Hi Alex,
the code to mock is DbSet in Microsoft Entity Framework.

BR
Christian
answered by ChristianL2 (3.1k points)
0 votes
Hi Christian,

The issue you raised regarding faking Microsoft Entity Framework classes is a complicated one and the solution depends on what you’re testing and what you’re trying to fake.

Faking DbSet is as easy as faking any other class. Bu it may not be enough.

For instance, in your code example, using: var items = _entityDbSet.Where(e => true); will return null because _entityDbSet is fake. It maybe that you want to return another value:

//Act
Var COLLECTION_OF_ENTITIES = new list…
Isolate.WhenCalled(() => _entityDbSet.Where(e => true)).WillReturn(COLLECTION_OF_ENTITIES );


But this may not solve your problem. That’s why it’s important for us to see what you’re trying to test.

By the way, in your example, both of the lines below are equivalent since Members.ReturnRecursiveFakes is the default parameter passed to Isolate.Fake.Instance<>().

//Arrange
var _entityDbSet = Isolate.Fake.Instance<DbSet<SomeEntityClass>>();

//Arrange?
//_entityDbSet = Isolate.Fake.Instance<DbSet<SomeEntityClass>>(Members.ReturnRecursiveFakes);


I hope it will answer your question!
answered by NofarC (4k points)
How would this look with the VB.Net syntax? I notice there is no "Isolate"? Thanks!
...