Question

I am trying to get my feet wet with asp.net mvc3 and unit testing.

I have created a model which uses the repository pattern. Here's the interface:

public interface IExtensionRepository
{
    IList<Extensions> ListAll();
}

Here's the repository:

public class ExtensionRepository : IExtensionRepository
{
    private ExtensionsLSDataContext _dataContext;

    public ExtensionRepository()
    {
        _dataContext = new ExtensionsLSDataContext();
    }

    public IList<Extensions> ListAll()
    {
        var extensions = from ext in _dataContext.Extensions
                         select ext;
        return extensions.ToList();
    }

}

Here's the controller:

public class ExtensionController : Controller
{

    private IExtensionRepository _repository;

    public ExtensionController()
        : this(new ExtensionRepository())
    {

    }

    public ExtensionController(IExtensionRepository repository)
    {
        _repository = repository;
    }
 }

The pages seem to function as designed. Things go astray with my unit test, however. It resides in another project in the same solution. I am using Moq and NUnit. Here's my test:

    [Test]
    public void Test_Extension_Index_Views()
    {
        Mock<Extensions> extension = new Mock<Extensions>();
        List<Extensions> extList = new List<Extensions>();
        extension.Object.Extension = "5307";
        extension.Object.Extension_ID = 1;
        extension.Object.ExtensionGroup_ID = 1;
        extList.Add(extension.Object);

        Mock<IExtensionRepository> repos = new Mock<IExtensionRepository>();
        repos.Setup(er => er.ListAll()).Returns(extList);

        var controller = new ExtensionController(repos);                       


        var result = controller.Index() as ViewResult;
        Assert.AreEqual("Index", result.ViewName);
    }

I am getting the following errors for the line that begins "var controller...":

The best overloaded method match for 'MvcApplication1.Controllers.ExtensionController.ExtensionController(MvcApplication1.Models.IExtensionRepository)' has some invalid arguments

And:

Argument 1: cannot convert from 'Moq.Mock' to 'MvcApplication1.Models.IExtensionRepository'

I know I've missed the boat somewhere, but I haven't a clue as to where... any ideas?

Was it helpful?

Solution

Change this:

var controller = new ExtensionController(repos); 

to this:

var controller = new ExtensionController(repos.Object);

PS.: I know it sucks, but that's the way Moq was designed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top