|
ASP.NET developers have long searched for an easy, effective tool for unit testing their code. Typemock Isolator has come to the rescue by making it easy to test ASP.NET or ASP.NET MVC code without changing it. The problem with unit testing ASP.NET Typemock Isolator's solution If this is still not sufficient and you’d like to test code-behind of ASP.NET pages, you can also use Ivonna, the web add-on to Isolator. With Ivonna, you‘ll get even easier APIs to simulate everything you need to test code-behind pages, like event handlers or the Page object. Isolator's ASP.NET unit test in action
public class ResponseWriter { public void WriteBoldNameToBrowser(string name) { // Create the tag string boldName = "" + name + "";
// Write the tag to the client HttpContext.Current.Response.Write(boldName); } }
How can we test that the method works correctly? There are two problems with testing it:
Let’s now see how we can test it with Isolator:
[TestMethod] public void WriteBoldNameToBrowser_FakeHTTPContext_WritesBold() { // Fake the HttpContext object, but also its childeren objects // including Response in a single line! Isolate.WhenCalled(()=>HttpContext.Current).ReturnRecursiveFake();
// Invoke the method ResponseWriter writer = new ResponseWriter(); writer.WriteBoldNameToBrowser("test");
// Verify the chain of calls occured with the correct arguments Isolate.Verify.WasCalledWithExactArguments(() => HttpContext.Current.Response.Write("test")); }
Note that we use Isolator for two purposes. The first is to fake HttpContext and any of its called variables. Using a Recursive Fake every object, starting from the HttpContext root, is faked by default - no need to build a tree of fake objects. That means no NullReferenceException from the Response property or its Write method. The second is that, instead of analyzing HTML code, we can simply make sure that the Write call was made with the correct arguments, using Isolate.Verify APIs. We now have an easy, quick and readable ASP.NET unit test! Download a free trial of Typemock's ASP.NET Unit Testing tool to start writing your own ASP.NET tests or click through our resources below for all the information and support you need to effectively unit test in ASP.NET.
Download Typemock Isolator ASP.NET Testing Tool! ASP.NET Unit Testing Resources:
|