With sample codes below,
public class RolesController : ApiController
{
private readonly IRoleService _roleService;
public RolesController(IRoleService roleService)
{
_roleService = roleService;
}
public async Task<IHttpActionResult> Get()
{
return Ok(await Task.FromResult(new[] { "value1", "value2" }));
}
}
public static class TestExtensions
{
public static async Task<HttpResponseMessage> ExecuteRequestAsync<C, A>(this C controller, Expression<Func<C, A>> methodExpressionCall)
{
var methodCall = methodExpressionCall.Body as MethodCallExpression;
var routeAttributes = methodCall.Method.GetCustomAttributes(typeof(RouteAttribute), true);
var routeName = string.Empty;
if (routeAttributes.Count() == 0 || string.IsNullOrEmpty(((RouteAttribute)routeAttributes[0]).Name))
routeName = methodCall.Method.Name.ToLower();
else
routeName = ((RouteAttribute)routeAttributes[0]).Name;
var config = new HttpConfiguration();
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
using (var client = new HttpClient(new HttpServer(config)))
{
return await client.GetAsync("http://localhost/api/roles/" + routeName);
}
}
}
[Fact]
public void OnCreate_ReturnTrue_IfInputDataAreValid()
{
var roleController = new RolesController(new RoleService());
//Act
var response = roleController.ExecuteRequestAsync(c => c.Get());
//Assert
Assert.Equal(HttpStatusCode.OK, response.Result.StatusCode);
}
Why is HttpClient returning Internal Server Error (500) on the API controller with parameterized constructor? See this code "roleController.ExecuteRequestAsync()".
Please note that IoC have been configured and working fine.