3

I've made a custom model, and I want to mock it. I'm fairly new to MVC, and very new to unit testing. Most approaches I've seen create an interface for the class and then make a mock that implements the same interface. However I can't seem to get this to work when actually passing the interface into the View. Cue "simplified" example:

Model-

public interface IContact
{
    void SendEmail(NameValueCollection httpRequestVars);
}

public abstract class Contact : IContact
{
    //some shared properties...
    public string Name { get; set; }

    public void SendEmail(NameValueCollection httpRequestVars = null)
    {
        //construct email...
    }
}

public class Enquiry : Contact
{
    //some extra properties...
}

View-

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<project.Models.IContact>" %>

<!-- other html... -->

<td><%= Html.TextBoxFor(model => ((Enquiry)model).Name)%></td>

Controller-

    [HttpPost]
    public ActionResult Index(IContact enquiry)
    {
        if (!ModelState.IsValid)
            return View(enquiry);

        enquiry.SendEmail(Request.ServerVariables);
        return View("Sent", enquiry);
    }

Unit Testing-

    [Test]
    public void Index_HttpPostInvalidModel_ReturnsDefaultView()
    {
        Enquiry enquiry = new Enquiry();
        _controller.ModelState.AddModelError("", "dummy value");

        ViewResult result = (ViewResult)_controller.Index(enquiry);

        Assert.IsNullOrEmpty(result.ViewName);
    }

    [Test]
    public void Index_HttpPostValidModel_CallsSendEmail()
    {
        MockContact mock = new MockContact();

        ViewResult result = (ViewResult)_controller.Index(mock);

        Assert.IsTrue(mock.EmailSent);
    }

public class MockContact : IContact
{
    public bool EmailSent = false;

    void SendEmail(NameValueCollection httpRequestVars)
    {
        EmailSent = true;
    }
}

Upon a HttpPost I get a "Cannot create an instance of an interface" exception. I seems that I can't have my cake (passing a model) and eat it (pass mock for unit testing). Maybe there's a better approach to unit testing models bound to views?

thanks,

Med

2
  • 2
    btw, a "model" normally doesn't contain logic (such as SendEmail())
    – user1228
    Nov 11, 2010 at 17:28
  • Let's not open the can-of-worms that is skinny/fat controller/model! Where do you think SendEmail() should go?
    – med4th
    Nov 11, 2010 at 17:59

3 Answers 3

9

I'm going to throw it out there, if you need to mock your models you're doing it wrong. Your models should be dumb property bags.

There is absolutely no reason that your model should have a SendEmail method. That is functionality that should be invoked from a controller calling to an EmailService.

Responding to your question:

After years of working with Separation of Concern (SOC) patterns like MVC, MVP, MVVM and seeing articles from people brighter than me (I wish I could find the one I'm thinking off about this but maybe I read it in a magazine). You will eventually conclude in an enterprise application you will end up with 3 distinct sets of model objects.

Previously I was a very big fan of doing Domain Driven Design (DDD) using a single set of business entities that were both plain old c# objects (POCO) and Persistent Ignorant (PI). Having domain models that are POCO/PI leaves you with a clean slate of objects where there is no code related to accessing the object storage or having other attributes that have schematic meaning for only 1 area of the code.

While this works, and can work fairly well for a period of time, there is eventually a tipping point where the complexity of expressing the relationship between View, Domain Model, and Physical Storage Model becomes too complex to express correctly with 1 set of entities.

To solve the impedance mismatches of View, Domain and Storage you really need 3 sets of models. Your ViewModels will exactly match your views binding to facilitate it to be easy to work with the UI. So this will frequently have things such as adding a List to populate drop downs with values that are valid for your edit view/action.

In the middle is the Domain Entities, these are the entities that you should validate against your business rules. So you will map to/from them on both sides to/from the view and to/from the storage layer. In these entities is where you could attach your code to do validation. I personally am not a fan of using attributes and coupling validation logic into your domain entities. It does make alot of sense to couple validation attributes into your ViewModels to take advantage of the built in MVC client side validation functionality.

For validation I would recommend using a library like FluentValidation (or your own custom one, they're not hard to write) that lets you separate your business rules from your objects. Although with new features with MVC3 you can do remote validation severside and have it display client side, this is an option to handle true business validation.

Finally you have your storage models. As I said previously I was very zealous on having PI objects being able to be reused through all layers so depending on how you setup your durable storage you might be able to directly use your domain objects. But if you take advantage of tools like Linq2Sql, EntityFramework (EF) etc you will most likely have auto generated models with code for interacting with the data provider so you will want to map your domain objects to your persistence objects.

So wrap all of this up this would be a standard logic flow in MVC actions

User goes to edit product page

  1. EF queries the database to get the existing product information, inside the repository layer the EF data objects are mapped to the Business Entities (BE) so all the data layer methods return BEs and have no external coupling to the EF data objects. (So if you ever change your data provider you don't have to alter a single line of code except for the internal implementation)

  2. The controller gets the Product BE and maps it to a Product ViewModel (VM) and adds collections for the different options that can be set for drop down lists

  3. Return View(theview, ProductVM)

User edits the product and submits the form

  1. Client side validation is passed (useful for date validation / number validation instead of having to submit the form for feedback)

  2. The ProductVM gets mapped back to ProductBE at this point you would validate the business rules along the lines ValidationFactory.Validate(ProductBE), if it's invalid return messages back to view and cancel edit, otherwise continue

  3. You pass the ProductBE into your repository model, inside the internal implementation of the data layer you map the ProductBE to the Product Data Entity for EF and update the database.

2016 edit: removed usages of Interface as separation of concerns and interfaces are entirely orthogonal.

2
  • That pattern is working for me. So in summary, ViewModels should be "property bags" and the rest of the Model classes provide the business rules to utilize them (and keep the Controllers skinny)?
    – med4th
    Nov 12, 2010 at 9:19
  • 1
    Having recently migrated an application from using CodeSmith to Linq2Sql, that SOC would've shaved off weeks. It's a shame I'm too new here to bump your score ;-)
    – med4th
    Nov 12, 2010 at 18:21
0

Your issue is here:

public ActionResult Index(IContact enquiry)

MVC in the background has to create a concrete type to pass to the method when calling it. In this method's case, MVC needs to create a type which implements IContract.

Which type? I dunno. Neither does MVC.

Instead of using interfaces in order to be able to mock your models, use normal classes that have protected methods which you can override in mocks.

public class Contact
{
    //some shared properties...
    public string Name { get; set; }

    public virtual void SendEmail(NameValueCollection httpRequestVars = null)
    {
        //construct email...
    }
}

public class MockContact
{
    //some shared properties...
    public string Name { get; set; }
    public bool EmailSent {get;private set;}

    public override void SendEmail(NameValueCollection vars = null)
    {
       EmailSent = true;
    }
}

and

public ActionResult Index(Contact enquiry)
1
  • Thanks for the quick reply, Will. How is MockContact related to Contact? Don't they have to be related, in order to both be passed into controller.Index(model)?
    – med4th
    Nov 11, 2010 at 18:00
0

It is possible to use interfaces.

See: http://mvcunity.codeplex.com/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.