blazer
blazer

Reputation: 21

moq testing void method for Delete

i need some help for testing a void method. can someone explan how void methods work with testing.

my services look like this:

public void DeleteUser(int userId)
 {
    var user = _dbcontext.Users.FirstOrDefault(usr => usr.Id == userId);
    {
        if (user != null)
        {
            _dbcontext.Users.Remove(user);
        }

    _dbcontext.SaveChanges();
    }
}




[TestClass]
public class UnitTest
{
    [TestMethod]
    public void DeleteUser()
    {
        mockContext = new Mock<UserService>();
        mockContext.SetUp(x => x.Users(It.IsAny<int>()).Returns(userid)
    }
}

Upvotes: 0

Views: 900

Answers (1)

Ilya Chernomordik
Ilya Chernomordik

Reputation: 30205

Void methods can do two important things:

  1. Edit state
  2. Call some other methods

Since your method do not edit state directly what you want to test is that Remove and SaveChanges was called if the user is found and not call anything if not.

Mock has a special Verify method that you can use for both cases. Here is example how to verify that SaveChanges was called (which you can put inside if by the way):

mockContext
   .Verify(c => c.SaveChanges(), Times.Once());

Or (the case where user does not exist):

mockContext
   .Verify(c => c.SaveChanges(), Times.Never());

Upvotes: 3

Related Questions