How to write Unit test for Action that raise an HttpException using StatusCode 404

I have an action below in a controller that throws an HttpException with a status of 404 :

public async Task<ActionResult> Edit(int id)
{
    Project proj = await _service.GetProjectById(id);
    if( proj == null)
    {
        throw new HttpException(404, "Project not found.");
    }
}

To test this scenario, I wrote a test case below, where I catch an AggregationException and throw an InnerException, which is expected as an HttpException:

[TestMethod]
[ExpectedException(typeof(HttpException),"Project not found.")]
public void Edit_Project_Load_InCorrect_Value()
{
    Task<ActionResult> task = _projectController.Edit(3);
    try
    {
        ViewResult result = task.Result as ViewResult;
        Assert.AreEqual("NotFound", result.ViewName, "Incorrect Page title");
    }
    catch (AggregateException ex)
    {
        throw ex.InnerException;
    }
}

This test run succeeds and returns an ExpectedException. I have two questions:

  • Is this the right way to write a unit test or is there a more gracious way to test it.
  • Is it possible to check Unit Test this user gets the correct error page (NotFound in this case).
+4
1

. AssertHelpers.cs, . , , ExpectedException, , ExpectedException , , , . , 404, 200, .

public static void RaisesException<TException>(Action dataFunction, string exceptionIdentifier = null)
{
    bool threwException = false;

    try
    {
        dataFunction();
    }
    catch (Exception e)
    {
        threwException = true;
        Assert.IsInstanceOfType(e, typeof(TException));
        if (exceptionIdentifier != null)
            Assert.AreEqual(exceptionIdentifier, e.Message);
    }

    if (!threwException)
        Assert.Fail("Expected action to raise exception with message: " + exceptionIdentifier);
}
+1

Source: https://habr.com/ru/post/1548241/


All Articles