C#C
C#3y ago
3 replies
Iheuzio

❔ Moq test exception thrown after adding and saved changes to the context object

Exception has occurred: CLR/Moq.MockException
Exception thrown: 'Moq.MockException' in Moq.dll: '
Expected invocation on the mock once, but was 0 times: m => m.Add(It.IsAny<User>())

Performed invocations:

   Mock<DbSet<User>:1> (m):

      DbSet<User>.ToString()
      DbSet<User>.ToString()
      DbSet<User>.ToString()'
   at Moq.Mock.Verify(Mock mock, LambdaExpression expression, Times times, String failMessage)
   at studyPalsTests.UserTests.CreateAccount() in c:\dev\c#\projects\410project\studyPalsTests\UserTests.cs:line 110


public void CreateAccount()
    {
        // arramge using mock for users
        var mockSet = new Mock<DbSet<User>>();
        var mockContext = new Mock<StudyAppContext>();
        mockContext.Setup(m => m.Users).Returns(mockSet.Object);
        var service = new UserManager(mockContext.Object);

        // act
        service.addUser(user);

        // assert to check if the user was added
        try
        {
            mockSet.Verify(m => m.Add(It.IsAny<User>()), Times.Once()); // exception is thrown here
            mockContext.Verify(m => m.SaveChanges(), Times.Once());
        }
        catch (System.Exception)
        {
            throw;
        }
    }
image.png
image.png
Was this page helpful?