Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3842746
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T15:50:16+00:00 2026-05-19T15:50:16+00:00

I try to test my controller [TestMethod] public void Index() { AdminController controller =

  • 0

I try to test my controller

[TestMethod]
    public void Index()
    {
        AdminController controller = new AdminController();
        ViewResult result = controller.Index() as ViewResult;
        Assert.IsNotNull(result);
    }

Here is Index() code:

public ActionResult Index()
        {
            var repository = new PostsRepository();
            var posts = repository.GetAllPosts();

            return View(posts);
        }

Repository:

public class PostsRepository : IPostsRepository
    {
        PostsDataContext _dataContext = new PostsDataContext();

        public IQueryable<Post> GetAllPosts()
        {
            var posts = from t in _dataContext.Posts select t;
            return posts;
        }

        public Post GetPostById(int id)
        {
            var post = from t in _dataContext.Posts
                       where t.id == id
                       select t;
            return post.First();
        }
    }

But my Index() unit test fails with error:

Test method MvcBlog.Tests.Controllers.AdminControllerTest.Index threw exception: 
System.NullReferenceException: Object reference not set to an instance of an object.

Stack Trace:

MvcBlog.Models.PostsDataContext..ctor() in C:\Users\cL1Nk3r\Documents\Visual Studio 2010\Projects\MvcBlog\MvcBlog\Models\Posts.designer.cs: line 38
MvcBlog.Repository.PostsRepository..ctor() in C:\Users\cL1Nk3r\Documents\Visual Studio 2010\Projects\MvcBlog\MvcBlog\Repository\PostsRepository.cs: line 11
MvcBlog.Controllers.AdminController.Index() in C:\Users\cL1Nk3r\Documents\Visual Studio 2010\Projects\MvcBlog\MvcBlog\Controllers\AdminController.cs: line 19
MvcBlog.Tests.Controllers.AdminControllerTest.Index() in C:\Users\cL1Nk3r\Documents\Visual Studio 2010\Projects\MvcBlog\MvcBlog.Tests\Controllers\AdminControllerTest.cs: line 19

Why it is an error?

If i just run my application, it works correctly.

Source code download: http://dl.dropbox.com/u/14053604/MvcBlog.rar

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-19T15:50:17+00:00Added an answer on May 19, 2026 at 3:50 pm

    The problem is the following line in your controller action:

    var repository = new PostsRepository();
    

    Here you are tying your controller to a particular implementation of the repository making it very difficult to unit test in isolation. In order to achieve weaker coupling between your controller and data access layer I would recommend you using constructor injection:

    public class PostsController: Controller
    {
        private readonly IPostsRepository _repository;
        public PostsController(IPostsRepository repository)
        {
            _repository = repository;
        }
    
        public ActionResult Index()
        {
            var posts = _repository.GetAllPosts();
            return View(posts);
        }
    }
    

    Now your controller is completely decoupled from a particular implementation of a repository which might depend on a database, etc. Now you could use a mocking framework such as Rhino Mocks or Moq to provide a dummy implementation of this repository for the unit test.

    Personally I like very much MVCContrib TestHelper which works with Rhino Mocks and allows for very elegant unit tests of controller actions. So once you’ve decoupled your controller from a specific implementation of the repository as I showed you could have the following unit test:

    [TestMethod]
    public void PostsController_Index_Action_Should_Fetch_All_Posts_From_Repository()
    {
        // arrange
        var postsRepositoryStub = MockRepository.GenerateStub<IPostsRepository>();
        var sut = new PostsController(postsRepositoryStub);
        var expectedPosts = new Post[0];
        postsRepositoryStub.Stub(x => x.GetAllPosts).Return(expectedPosts);
    
        // act
        var actual = sut.Index();
    
        // assert
        actual
            .AssertViewRendered()
            .WithViewData<IEnumerable<Post>>()
            .ShouldBe(expectedPosts);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have two test method calling to controller: This one passed: [Test] public void
When I try this code: a, b, c = (1, 2, 3) def test():
I'm starting to try and test my Doctrine objects with PHPUnit, and would like
I try to fetch a Wikipedia article with Python's urllib: f = urllib.urlopen(http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes) s
We try to convert from string to Byte[] using the following Java code: String
I am trying to test a Controller that has a Command object with data
How can one best test a controller action which receives a file upload using
I wrote Front Controller Pattern and ran the test. Somehow request.getPathInfo() is returning null
Is there a way to test if a collection is already initialized? try-catch only?
I am writing a test case against a controller that returns a pdf file.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.