[Test]
public void Post_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(expression => expression.Find("continuing-to-an-outer-loop"))
.Returns(post);
var viewResult = (ViewResult) controller.Post("continuing-to-an-outer-loop");
var actual = viewResult.Model as PostViewModel;
Assert.NotNull(actual);
Assert.AreEqual(actual.Slug, post.Slug);
Assert.AreEqual(actual.Title, post.Title);
Assert.AreEqual(actual.Summary, post.Summary);
Assert.AreEqual(actual.Content, post.Content);
Assert.AreEqual(actual.PublishedAt, post.PublishedAt);
Assert.AreEqual(actual.Tags, post.Tags);
}
Hopefully the purpose of this test is already clear but to further clarify - the repository exposes a Post
object that is mapped to a PostViewModel
. I then proceed to assert that the action method returns the correct model.
The action method looks like this:
public ActionResult Post(string slug)
{
Post post =
repository.Find(slug);
if (post == null || post.Draft)
{
return HttpNotFound();
}
return View("Post", post.MapTo<PostViewModel>());
}
Could you please review this test? My particular areas of concern are as follows:
- Is the test well named? (I adopted the name from here).
- Must I assert that each property is equal as I have above? I feel as though I can make a reasonable assumption that if one property is equal then the rest will be too.
- Here I am modelling the
post
object based on a real blog post. I do not think that the value of each property really matters and that I could very well have used arbitrary strings. Are there any best practices regarding which test data to use? - Would it be reasonable to extract the
post
object to another class and expose it using a factory of sorts? This will reduce the ceremony of my test and keep things DRY. Are there any best practices regarding this?