Our first tests in C#

Have you ever created a new MVC project in Visual Studio? Have you noticed the checkbox towards the bottom of the dialog box? Have you ever selected, Create Unit Test Project? The tests created with this Unit Test Project are largely of little use. They do little more than validate that the default MVC controllers return the proper type. This is perhaps one step beyond, ItExists. Let's look at the first set of tests created for us:

using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SampleApplication.Controllers;

namespace SampleApplication.Tests.Controllers
{
[TestClass]
public class HomeControllerTest
{
[TestMethod]
public void Index()
{
// Arrange
HomeController controller = new HomeController();

// Act
ViewResult result = controller.Index() as ViewResult;

// Assert
Assert.IsNotNull(result);
}

[TestMethod]
public void About()
{
// Arrange
HomeController controller = new HomeController();

// Act
ViewResult result = controller.About() as ViewResult;

// Assert
Assert.AreEqual("Your application…", result.ViewBag.Message);
}

[TestMethod]
public void Contact()
{
// Arrange
HomeController controller = new HomeController();

// Act
ViewResult result = controller.Contact() as ViewResult;

// Assert
Assert.IsNotNull(result);
}
}
}

Here, we can see the basics of a test class, and the test cases contained within. Out of the box, Visual Studio ships with MSTest, which is what we can see here. The test class must be decorated with the [TestClass] attribute. Individual tests must likewise also be decorated with the [TestMethod] attribute. This allows the test runner to determine which tests to execute. 

For now, we can see that the HomeController is being tested. Each of the public methods has a single test, for which you may want to create additional tests and/or extract tests to separate files in the future. Later we'll be covering options and best practices to help you arrange your files in a much more manageable fashion. All of this should be part of your refactor step in your red, green, refactor cycle.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.49.243