0

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)
    }
}
mag_zbc
  • 6,801
  • 14
  • 40
  • 62
blazer
  • 21
  • 2
  • where is the void method you want to test ? – BRAHIM Kamel Sep 27 '17 at 09:51
  • Doing unit tests on actual database is not a good option, also if you are not using IoC there is no need for Moq here and it wont work if your class is not virtual. Besides that rethink what you really want to achieve with that test – erexo Sep 27 '17 at 09:57
  • See the related questions down the side. This may be a duplicate of one of those. – Ben Aaronson Sep 27 '17 at 10:06
  • may be this can help https://stackoverflow.com/questions/15805812/mock-an-update-method-returning-a-void-with-moq – BRAHIM Kamel Sep 27 '17 at 10:10

1 Answers1

3

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());
Ilya Chernomordik
  • 27,817
  • 27
  • 121
  • 207