TypeMock - Unit test for ASP.NET class utilities

For our CASK application I am creating a User Import module; I have to import a list of names from an old .NET 1.1 Newsletter application (xml file) into CASK so my client can use it's Newsletter capabilities with existing users.  A user import module (reusable) seemed to be the way to go.

Although a simple utility, I have made a commitment to do TDD from now on so a lot of infrastructure has to be put in place to support it; e.g., the simple process below has to be supported from Unit Test:

The HttpContextBase class takes on the responsibility of ensuring that there is an HttpContext.Current instance; it takes care of this responsibility in it's constructor:


Note: I moved the PhysicalPath line path below line 38 (so it is always set) 

The HttpContext.Current.Server object is a different story - it won't allow me to instantiate a HttpServerUtility object; it is inaccessible.   For this we'll rely on TypeMock; I chose it primarily because it supports SharePoint sealed classes and they have graciously offered us (the open source community) a free licence to use it with our projects.  

Below I configure TypeMock so that when a request for Server.MapPath("App_data") is made that it will return the MockFolderPath; I'll be using this as a location to place the <user>.XML file uploaded via the ASP FileUpload control.

[TestClass]
public class FileUploadUtilFixture :
TestBase
{

[TestMethod]
public void
HttpContext_CanGetContextForUnitTest()
{
    // The TestBase:HttpContextBase constructor will

    // create a HttpContext.Current if it is null
    HttpContext context = HttpContext.Current;
    Assert.IsNotNull(context,
"HttpContextBase should create HttpContext"
);
    Assert.IsNotNull(PhysicalPath);

    // Dynamically generate our MockFolderPath using the

    // TestBase:HttpContextBase.PhysicalPath property (the
    // baseclass used by FileUploadUtil).
    MockFolderPath = PhysicalPath.Replace("default.aspx", "App_Data"
);

    // Instantiate our file Utility class

    FileUploadUtil fileUploadUtil = new
FileUploadUtil();

    // When MapPath("App_Data") is requested supply our

    // MockFolderPath (public static string in TestBase)
    using
(RecordExpectations recorder = RecorderManager.StartRecording())
    {
        HttpContext.Current.Server.MapPath("App_Data"
);
        recorder.Return(MockFolderPath);
    }

    // Use the fileUploadUtil to retrieve our data path

    string
app_dataPath = fileUploadUtil.GetFileFolder();

    // Assert that all is well

    Assert.AreEqual(app_dataPath, MockFolderPath);
    Assert.AreEqual(MockFolderPath, fileUploadUtil.FileFolder);

    MockManager.Verify();
}

Full source code available HERE Change Set: 40436


Tags: , ,
Categories:


Actions: E-mail | Permalink |  Grammar/Typo/Better way? Please let me know