I am getting started with unit testing using xUnit.net and Moq. I am writing a test method for the Update() method in AppService:
public class AppService : IAppService
{
   public virtual void Update(App entity)
   {
       if (entity == null)
       {
           throw new ArgumentNullException("App");
       }
       _appRepository.Update(entity);
       _cacheManager.Remove(Key);
   }
}
_appRepository and _cacheManager derive from interfaces IRepository<App> and ICacheManager, respectively. I am using moq to create mocks of these objects in my unit test, shown below:
[Fact]
public void UpdateTest()
{
     mockAppRepository = new Mock<IRepository<App>>();
     mockCacheManager = new Mock<ICacheManager>();
     // how to setup mock?
     // mockAppRepository.Setup();
     AppService target = new AppService(mockAppRepository.Object, 
          mockCacheManager.Object);
     App entity = new App();
     target.Update(entity);
     Assert.NotNull(entity);
}
I understand I need the mock to simulate that an update in the repository succeeded, specifically the call to _appRepository.Update(entity); 
My question is, what is the best way to do this? Should I just use a Callback method when I call Setup() on the mockAppRespository? Is it standard to create a dummy collection and set the expectation on the update method to modify the dummy collection?
Usually a test as simple as this will do.
mockAppRepository.Verify(d=> d.Update(It.IsAny<App>()), Times.Once());
With Moq you only need to .Setup() a test like this if the return result is important.
Edit:
To illustrate throwing an exception, as per comments, you would do the following setup before running your code.
mockAppRepository.Setup(d=> d.Update(It.IsAny<App>())).Throws<Exception>();
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With