Sample 2: Mocking HttpContext and HttpRequest

Original Method

The following sample includes a function that creates a new Client with the data from the Request.Form and adds it to the Json file with all the existing clients.

C#
public ActionResult Create()
{
    ViewBag.Submitted = false;

    var created = false;
    // Create the Client
    if (HttpContext.Request.RequestType == "POST")
    {
        ViewBag.Submitted = true;
        // If the request is POST, get the values from the form
        var id = Request.Form["id"];
        var name = Request.Form["name"];
        var address = Request.Form["address"];
        var trusted = false;

        if (Request.Form["trusted"] == "on")
        {
            trusted = true;
        }

        // Create a new Client for these details.
        Client client = new Client()
        {
            ID = Convert.ToInt16(id),
            Name = name,
            Address = address,
            Trusted = Convert.ToBoolean(trusted)
        };

        // Save the client in the ClientList
        var ClientFile = Client.ClientFile;
        var ClientData = System.IO.File.ReadAllText(ClientFile);
        List<Client> ClientList = new List<Client>();
        ClientList = JsonConvert.DeserializeObject<List<Client>>(ClientData);

        if (ClientList == null)
        {
            ClientList = new  List<Client>();
        }
        ClientList.Add(client);

        // Now save the list on the disk
        System.IO.File.WriteAllText(ClientFile, JsonConvert.SerializeObject(ClientList));

        // Denote that the client was created
        created = true;
    }

    if (created)
    {
        ViewBag.Message = "Client was created successfully.";
    }
    else
    {
        ViewBag.Message = "There was an error while creating the client.";
    }
    return View();
}

VB
Public Function Create() As ActionResult

    ViewBag.Submitted = False

    Dim created = False
    ' Create the Client
    If HttpContext.Request.RequestType = "POST" Then
        ViewBag.Submitted = True
        ' If the request is POST, get the values from the form
        Dim id = Request.Form("id")
        Dim name = Request.Form("name")
        Dim address = Request.Form("address")
        Dim trusted = False

        If Request.Form("trusted") = "on" Then
            trusted = True
        End If

        ' Create a new Client for these details.
        Dim client__1 As New Client() With {
        .ID = Convert.ToInt16(id),
        .Name = name,
        .Address = address,
        .Trusted = Convert.ToBoolean(trusted)
    }

        ' Save the client in the ClientList
        Dim ClientFile = Client.ClientFile
        Dim ClientData = System.IO.File.ReadAllText(ClientFile)
        Dim ClientList As New List(Of Client)()
        ClientList = JsonConvert.DeserializeObject(Of List(Of Client))(ClientData)

        If ClientList Is Nothing Then
            ClientList = New List(Of Client)()
        End If
        ClientList.Add(client__1)

        ' Now save the list on the disk
        System.IO.File.WriteAllText(ClientFile, JsonConvert.SerializeObject(ClientList))

        ' Denote that the client was created
        created = True
    End If

    If created Then
        ViewBag.Message = "Client was created successfully."
    Else
        ViewBag.Message = "There was an error while creating the client."
    End If
    Return View()
End Function

Simple Scenario:

Typemock Isolator Features Used

Modify methods behavior

Mock HttpContext

Mock HttpRequest

Scenario

1. Create ClientController because it is our class under test.

2.Fake ClientController.HttpContext.Request.RequestType to be "GET".

3. Call ClientController.Create and check the result using Assertions.

Code
C#
[TestMethod, Isolated]
public void TestWhenClientRequestTypeIsGet_ErrorMessageIsShown ()
{
    // Arrange
    // Create the wanted controller for testing
    var controller = new ClientController();

    // Fake HttpContext and RequestType to be "GET"
    Isolate.WhenCalled(() => controller.HttpContext.Request.RequestType).WillReturn("GET");
   
    // Act
    var result = controller.Create() as ViewResultBase;
  
    // Assert
    // The result will be that there was an error while trying to created the Client and it wasn't submitted.
    Assert.AreEqual("There was an error while creating the client.", controller.ViewBag.Message);
    Assert.AreEqual(false, controller.ViewBag.Submitted);
}

VB

<TestMethod(), Isolated()>
Public Sub TestWhenClientRequestTypeIsGet_ErrorMessageIsShown()
    ' Arrange
    ' Create the wanted controller for testing
    Dim controller = New ClientController()
    
    ' Fake HttpContext and RequestType to be "GET"
    Isolate.WhenCalled(Function() controller.HttpContext.Request.RequestType).WillReturn("GET")
    
    ' Act
    Dim result = TryCast(controller.Create(), ViewResultBase)
    
    ' Assert
    ' The result will be that there was an error while trying to created the Client and it wasn't submitted.
    Assert.AreEqual("There was an error while creating the client.", controller.ViewBag.Message)
    Assert.AreEqual(False, controller.ViewBag.Submitted)
End Sub

Advanced Scenario:

Typemock Isolator Features Used

Modify methods behavior

Ignore methods

Mock HttpContext

Mock HttpRequest

Scenario

1. Fake HttpContext.Current.Server.MapPath to return a fake file path.

2. Create ClientController because it is our class under test.

3. Fake ClientController.Request.Form to return the data that we what to be in the new Client.

4. Ignore File.ReadAllText and File.WriteAllText so the program won't try to write or read from the fake file.

5. Fake ClientController.HttpContext.Request.RequestType to be "POST" because "GET" won't pass the first "if".

6. Call ClientController.Create and check the result using Assertions and Verification.

Code
C#


[TestMethod, Isolated]
public void TestWhenClientCreationIsSuccessful_SuccessMessageIsShown()
{
    // Arrange
    // Fake HttpContext to return fake file path
    Isolate.WhenCalled(() => HttpContext.Current.Server.MapPath("")).WillReturn("mapPath");
   
    // Create the wanted controller for testing 
    var controller = new ClientController();

    // Fake HttpRequest 
    Isolate.WhenCalled(() => controller.Request.Form["id"]).WillReturn("0");
    Isolate.WhenCalled(() => controller.Request.Form["name"]).WillReturn("TypeMock");
    Isolate.WhenCalled(() => controller.Request.Form["address"]).WillReturn("TypeMockRocks");

    // Ignore File.ReadAllText and File.WriteAllText
    Isolate.WhenCalled(() => File.ReadAllText("")).WillReturn("");
    Isolate.WhenCalled(() => File.WriteAllText("", "")).IgnoreCall();

    // Fake HttpContext and RequestType to be "POST"
    Isolate.WhenCalled(() => controller.HttpContext.Request.RequestType).WillReturn("POST");
   
    // Act
    var result = controller.Create() as ViewResultBase;

    // Assert
    // The result will be that the Client was successfully created and had been submitted
    Assert.AreEqual("Client was created successfully.", controller.ViewBag.Message);
    Assert.AreEqual(true, controller.ViewBag.Submitted);
    // Verify that File.WriteAllText method was called with the correct arguments
    string jsonClientExpectedString = "[{\"ID\":0,\"Name\":\"TypeMock\",\"Address\":\"TypeMockRocks\",\"Trusted\":false}]";
    Isolate.Verify.WasCalledWithExactArguments(() => File.WriteAllText("mapPath", jsonClientExpectedString));
}

VB

<TestMethod(), Isolated()>
Public Sub TestWhenClientCreationIsSuccessful_SuccessMessageIsShown()
    ' Arrange
    ' Fake HttpContext to return fake file path
    Isolate.WhenCalled(Function() HttpContext.Current.Server.MapPath("")).WillReturn("mapPath")

    ' Create the wanted controller for testing 
    Dim controller = New ClientController()

    ' Fake HttpRequest 
    Isolate.WhenCalled(Function() controller.Request.Form("id")).WillReturn("0")
    Isolate.WhenCalled(Function() controller.Request.Form("name")).WillReturn("TypeMock")
    Isolate.WhenCalled(Function() controller.Request.Form("address")).WillReturn("TypeMockRocks")

    ' Ignore File.ReadAllText and File.WriteAllText
    Isolate.WhenCalled(Function() File.ReadAllText("")).WillReturn("")
    Isolate.WhenCalled(Sub() File.WriteAllText("", "")).IgnoreCall()

    ' Fake HttpContext and RequestType to be "POST"
    Isolate.WhenCalled(Function() controller.HttpContext.Request.RequestType).WillReturn("POST")

    ' Act
    Dim result = TryCast(controller.Create(), ViewResultBase)

    ' Assert
    ' The result will be that the Client was successfully created and had been submitted
    Assert.AreEqual("Client was created successfully.", controller.ViewBag.Message)
    Assert.AreEqual(True, controller.ViewBag.Submitted)
    ' Verify that File.WriteAllText method was called with the correct arguments
    Dim jsonClientExpectedString As String = "[{""ID"":0,""Name"":""TypeMock"",""Address"":""TypeMockRocks"",""Trusted"":false}]"
    Isolate.Verify.WasCalledWithExactArguments(Sub() File.WriteAllText("mapPath", jsonClientExpectedString))
End Sub