Skip to content

Instantly share code, notes, and snippets.

@dsolovay
Created August 8, 2016 19:09
Show Gist options
  • Save dsolovay/38188bbf6155c2910edcf44f24281945 to your computer and use it in GitHub Desktop.
Save dsolovay/38188bbf6155c2910edcf44f24281945 to your computer and use it in GitHub Desktop.
Demo of adding functionality to MVC controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using FluentAssertions;
using MvcSample.Controllers;
using NSubstitute;
using Xunit;
namespace MvcSampleTests
{
public class HomeControllerTests
{
private HomeController _sut;
private HttpContextBase _context;
public HomeControllerTests()
{
_sut = new HomeController();
_context = Substitute.For<HttpContextBase>();
_sut.ControllerContext = new ControllerContext(_context, new RouteData(), _sut);
}
[Fact]
public void Index_Called_ReturnsView()
{
var actionResult = _sut.Index();
actionResult.Should().BeOfType<ViewResult>();
}
[Fact]
public void Index_Called_IncrementsSessionViewCount()
{
_sut.Index();
var x = _context.Received().Session["ViewCount"];
}
[Fact]
public void Index_ViewCountNull_SetsToOne()
{
_context.Session["ViewCount"].Returns(null);
_sut.Index();
_context.Session.Received()["ViewCount"] = 1;
}
[Fact]
public void Index_HasValue_Increments()
{
_context.Session["ViewCount"].Returns(1);
_sut.Index();
_context.Session.Received()["ViewCount"] = 2;
}
[Fact]
public void Index_Count3_Redirect()
{
_context.Session["ViewCount"].Returns(3);
var result = _sut.Index() as RedirectResult;
result.Url.ShouldAllBeEquivalentTo("/home/about");
}
}
}
@dsolovay
Copy link
Author

dsolovay commented Aug 8, 2016

Some notes:

  • I hadn't yet dug into AutoFixture, or I probably would have made sut a parameter. But I think this lays out the AAA structure well.
  • The test at line 31 shows how you get started putting something under test. "Hey let's just see if I can run this and assert a result.
  • 39-73 start to eek out the functionality.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment