Reputation: 1942
I am trying to test my web api methods that are using async and they never return a result.
Here is the control method:
[HttpGet]
[Route("{id}")]
[ResponseType(typeof(IEmployee))]
public async Task<IHttpActionResult> Get(string id)
{
try
{
IEmployee result = await _repoEmployee.GetEmployeeAsync(id);
return Ok(result);
}
catch (Exception ex)
{
logit.Error($@"An error occurred while trying to get Employee for Employee number ""{id}"".", ex);
throw;
}
}
Here is the test using NUnit:
[TestCase("0677")]
public async Task EmployeeController_Get_GiveValidEmpID_Success(string employeeNumber)
{
Setup();
// Act
IHttpActionResult getResult = await _controller.Get(employeeNumber);
var contentResult = getResult as NegotiatedContentResult<IEmployee>;
// Assert
Assert.IsNotNull(contentResult);
Assert.AreEqual(HttpStatusCode.Accepted, contentResult.StatusCode);
Assert.IsNotNull(contentResult.Content);
Assert.AreEqual(employeeNumber, contentResult.Content.Person.EmployeeNumber);
}
If I debug the Get method the correct results appear in the result variable but when it gets back to the test method the getResult is nothing.
Where am I going wrong and how can I fix it in order to test the results?
Thanks!
Upvotes: 0
Views: 585
Reputation: 119146
Because getResult
is not of type NegotiatedContentResult<IEmployee>
the cast results in a null value for contentResult
. Instead, you probably want to cast to OkNegotiatedContentResult<IEmployee>
:
var contentResult = getResult as OkNegotiatedContentResult<IEmployee>;
Upvotes: 2