MichalJankowskii/Moq.EntityFrameworkCore

ReturnsDbSet only returns the set value on it's first call

Closed this issue · 1 comments

I've noticed that when I mock a DbSet for my context to return, the value is only returned on the first call. If I try to access the DbSet values again it returns no results.

mockContext.Setup(context => context.Formats).ReturnsDbSet(formats);

When I access Formats from my mocked context, the first call returns the data supplied to ReturnsDbSet(). However, any future call to Formats returns an empty list. Is there a way to ensure the data sticks around for multiple calls? Other than this oddity this has been working great. Thanks!

Could you provide code that will simulate your case?

I changed the first test from file UsersServiceTest.cs to:

[Fact]
public void Given_ListOfUsersWithOneUserAccountLock_When_CheckingWhoIsLocked_Then_CorrectLockedUserIsReturned()
{
  // Arrange
  IList<User> users = GenerateNotLockedUsers();
  var lockedUser = Fixture.Build<User>().With(u => u.AccountLocked, true).Create();
  users.Add(lockedUser);

  var userContextMock = new Mock<UsersContext>();
  userContextMock.Setup(x => x.Users).ReturnsDbSet(users);

  var usersService = new UsersService(userContextMock.Object);

  // Act
  var lockedUsers1 = usersService.GetLockedUsers();
  var lockedUsers2 = usersService.GetLockedUsers();
  var lockedUsers3 = usersService.GetLockedUsers();

  // Assert
  Assert.Equal(new List<User> {lockedUser}, lockedUsers1);
  Assert.Equal(new List<User> {lockedUser}, lockedUsers2);
  Assert.Equal(new List<User> {lockedUser}, lockedUsers3);
}

And I can get values more than one time. I would like to help you but I am not able to reproduce your case.