Question

the repository is a prop of an Mvc controller, i'm trying to write a test method to check this controller, but i get an error in the container call...

i'm new in mvc and testing.. so i dont know where to start how can i do this?

this is how the test looks like:

public void SomeTest()
    {
        var controller= new SomeController();
        var result = SomeController.Index();
        Assert.IsNotNull(result);
     } 

The error i recive when i run the test an exception of type System.NullReferenceException occurred in SomeContext.dll but was not handled in user code

Was it helpful?

Solution

Has your repository been initialized?
In your controller:

private Repository Repository {get;set;}

public ActionResult Index()
{
    Repository = new Repository();
    var something = Repository.DoSomeWork();
    return View(something);
}

In your test class:

public void SomeTest()
{
    var controller = new SomeController();

    var result = controller.Index();

    Assert.IsNotNull(result);
}

or if you are using dependency injection, with Ninject property injection you can try using Moq to inject the class:

public class SomeController : Controller
{
    private IRepository repository;

    [Inject]
    public IRepository Repository
    {
        get { return repository; }
        set { repository = value; }
    }

    // GET: /Some/
    public ActionResult Index()
    {
        var someCollection = Repository.SomeMethod("some parameter");

        foreach (var value in someCollection)
        {
            ViewData["message"] += value;
        }
        return View(someCollection);
    }
}

and the test class with moq:

public class SomeTestClass
{
    private Mock<IRepository> mockRepository;

    [Test]
    public void GivenSometestThenExpectSomeResult()
    {
        // Arrange
        var controller = new SomeController();

        mockRepository = new Mock<IRepository>();
        mockRepository.Setup(x => x.SomeMethod(It.IsAny<string>())).Returns(new List<string>());

        controller.Repository = mockRepository.Object;

        // Act
        ActionResult result = controller.Index();

        // Assert
        Assert.AreEqual("Index", result.ViewName);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top