asp.net mvc - How to create fake test objects quickly and efficiently

Posted by Simon G on Stack Overflow See other posts from Stack Overflow or by Simon G
Published on 2010-06-18T08:54:29Z Indexed on 2010/06/18 9:03 UTC
Read the original article Hit count: 414

Hi,

I'm currently testing the controller in my mvc app and I'm creating a fake repository for testing. However I seem to be writing more code and spending more time for the fakes than I do on the actual repositories. Is this right?

The code I have is as follows:

Controller

public partial class SomeController : Controller
{
    IRepository repository;

    public SomeController(IRepository rep)
    {
        repository = rep;
    }

    public virtaul ActionResult Index()
    {
        // Some logic
        var model = repository.GetSomething();

        return View(model);
    }
}

IRepository

public interface IRepository
{
    Something GetSomething();
}

Fake Repository

public class FakeRepository : IRepository
{
    private List<Something> somethingList;

    public FakeRepository(List<Something> somethings)
    {
        somthingList = somthings;
    }

    public Something GetSomething()
    {
        return somethingList;
    }
}

Fake Data

class FakeSomethingData
{
    public static List<Something> CreateSomethingData()
    {
        var somethings = new List<Something>();

        for (int i = 0; i < 100; i++)
        {
            somethings.Add(new Something
            {
                value1 = String.Format("value{0}", i),
                value2 = String.Format("value{0}", i),
                value3 = String.Format("value{0}", i)
            });
        }

        return somethings;
    }
}

Actual Test

[TestClass]
public class SomethingControllerTest
{
    SomethingController CreateSomethingController()
    {
        var testData = FakeSomethingData.CreateSomethingData();
        var repository = new FakeSomethingRepository(testData);

        SomethingController controller = new SomethingController(repository);

        return controller;
    }

    [TestMethod]
    public void SomeTest()
    {
        // Arrange
        var controller = CreateSomethingController();

        // Act
        // Some test here

        // Arrange
    }
}

All this seems to be a lot of extra code, especially as I have more than one repository. Is there a more efficient way of doing this? Maybe using mocks?

Thanks

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about unit-testing