testability considerations while creating controllers

Viewed 25

I am writing controllers in Web API 2, against which odata queries will be executed:

[Route("", Name = "GetAccount")]
[HttpGet]
public async Task<IHttpActionResult> GetAccount()
{
    var query = Request.RequestUri.PathAndQuery.Split('/')[2]; //this query variable will be something "filter=name eq 'alex'"
    var response = _accountService.Get(query);

    if (!response.Result.IsSuccessStatusCode)
    {
        return NotFound();
    }

    var readAsAsync = response.Result.Content.ReadAsAsync<object>();
    if (readAsAsync == null)
    {
        return NotFound();
    }

    var result = await readAsAsync;
    return Ok(result);
} 

How do I inject the Request, specifically as it relates to: var query = Request.RequestUri.PathAndQuery.Split('/')[2]; ?

Here's a very basic test that I've written for this controller:

[TestMethod]
public void GetAccount_Returns_IHttpActionResultTask()
{
    var accountsService = new Mock<IAccountService>();
    var sut = new AccountsController(accountsService.Object);

    Assert.IsInstanceOfType(sut.GetAccount(), typeof(Task<IHttpActionResult>));
}

In order to test with different values for Request.RequestUri...., how do I rewrite my controller to be more testable?

1 Answers
Related