Base solution for your next web application
Open Closed

How to mock an application service dependency in unit tests #1993


User avatar
0
djfuzzy created

In the Unit Testing tutorial, it is mentioned that we use real implementations of dependencies when unit testing. What if we do not want to do this? For instance, I have an application service method that queues a background job (using the default background job manager). When I am unit testing this method, I do not want the job to actually be queued (in this case, I am queuing a job to send out an email). I only want to verify that JobManager.EnqueueAsync is called by my service method. I tried playing around with Moq and Castle to get it to work but my JobManager is always the real implementation of it. I could always stub out the call to JobManager.EnqueueAsync, and set a flag that I can check to verify it has been called but then I'm not sure how to do that when its recommended to use Resolve <IMyApplicationService>() to obtain a reference to my application service. I appreciate any advice!


1 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    You can use NSubstitute for this one. We have used it in our paid product. See it's documentation here <a class="postlink" href="http://nsubstitute.github.io/">http://nsubstitute.github.io/</a>

    Or you can disalbe background job execution in your test module. See <a class="postlink" href="http://aspnetboilerplate.com/Pages/Documents/Background-Jobs-And-Workers#disabling-job-execution">http://aspnetboilerplate.com/Pages/Docu ... -execution</a>