How do I unit test the controller that returns the model?

I have a controller named PostsController

public class PostsController : Controller
{
    private readonly IPostsRepository repository;

    public PostsController(IPostsRepository repository)
    {
        this.repository = repository;
    }

    public ViewResult Index()
    {
        var posts =
            repository.All()
                      .OrderBy(post => post.PublishedAt);

        return View("Index", posts.MapTo<PostViewModel>());
    }
}

And the corresponding test fixture, called PostsControllerTest

[TestFixture]
public class PostsControllerTest
{
    private PostsController controller;
    private Mock<IPostsRepository> repository;

    [SetUp]
    public void SetUp()
    {
        AutoMapperConfig.Configure();
        repository = new Mock<IPostsRepository>();
        controller = new PostsController(repository.Object);
    }

    [Test]
    public void Index_ReturnsCorrectModel()
    {
        var actual = controller.Index().Model;

        Assert.IsAssignableFrom<IEnumerable<PostViewModel>>(actual);
    }
}

At the moment, I only check that the controller will return the correct type of model. Should I also mute the repository and verify that the correct data is returned as follows:

[Test]
public void Index_ReturnsCorrectModel()
{
    var post = new Post
    {
        Slug = "continuing-to-an-outer-loop",
        Title = "Continuing to an outer loop",
        Summary = "When you have a nested loop, sometimes",
        Content = "When you have a nested loop, sometimes",
        PublishedAt = DateTime.Now.AddDays(7),
        Tags = new Collection<Tag> { new Tag { Name = "Programming" } }
    };
    repository.Setup(repo => repo.All()).Returns(new[] { post });

    var actual = controller.Index().Model as IEnumerable<PostViewModel>;
    Assert.NotNull(actual);
    Assert.AreEqual(1, actual.Count());
    Assert.AreEqual(post.Title, actual.First().Title);
}

I feel so upset that I don’t know if I am testing the device correctly. A clear explanation of what I am approaching, I must understand why it would be very useful.

+4
source share
1 answer

, IPostRepository unit test. unit test .

, MapTo<T> .

SUT (System Under Test), Index PostsController.

, 2 , unit test:

1- repository.All()

2- ( )

unit test :

[Test]
    public void Index_ReturnsCorrectModel()
    {
        // Arrange
        repository.Setup(repo => repo.All()).Returns(Enumerable.Empty<Post>());

        // Act
        var actual = controller.Index().Model;

        // Assert
        Assert.IsAssignableFrom<IEnumerable<PostViewModel>>(actual);
        repository.Verify(repo => repo.All(), Times.Once);
    }

, , unit test, AutoFixture, post.

+2

All Articles