Search code examples
unit-testingasp.net-mvc-3moqmvcmailer

MvcMailer unit tests: System.ArgumentNullException httpContext cannot be null


I cannot successfully run unit tests for MvcMailer using the visual studio test suite and Moq. I have copied the example from the wiki word for word but get the following exception every time:

Test method MvcMailerTest.Tests.MailerTest.TestMethod1 threw exception: 
System.ArgumentNullException: Value cannot be null.
Parameter name: httpContext

Code is as follows: (Using the VS unit test framework - exact same error when using nUnit as in the example)

        //Arrange: Moq out the PopulateBody method
        var _userMailerMock = new Mock<UserMailer>();
        _userMailerMock.Setup(mailer => mailer.PopulateBody(It.IsAny<MailMessage>(), "Welcome", null));            
        _userMailerMock.CallBase = true;

        //Act
        var mailMessage = _userMailerMock.Object.Welcome();

Fails on the following line in the Welcome() method (copied straight out of the wiki):

 PopulateBody(mailMessage, viewName: "Welcome");

The wiki is here: https://github.com/smsohan/MvcMailer/wiki/MvcMailer-Step-by-Step-Guide

Similar (almost exactly the same) Question: MvcMailer: Can't complete NUnit tests on Razor Views which use Url.Action

Anyone know how to fix/get around this? The linked question says I need to mock out the PopulateBody method which I have done (as per wiki).


Solution

  • a workaround is to change your code to this:

    PopulateBody(mailMessage, "Welcome", null);

    This will work because you have a mock setup for that overload of PopulateBody and not for the 2 parameter version of it..