Is there an sample code that shows unit testing a controller that inherits from the api controller? I am trying to unit test a POST but it is failing. I believe I need to set up
Sample code for unit testing API controller with async fundtion in C#
Prepare test Models:
using System;
namespace TestAPI.Models
{
public class TestResult
{
public DateTime Date { get; set; }
public bool Success { get; set; }
public string Message { get; set; }
}
}
Prepare test controller
using TestAPI.Models;
using System;
using System.Net;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
namespace TestAPI.Controllers
{
public class TestController : ApiController
{
public TestController()
{
}
[HttpPost]
[ResponseType(typeof(TestResult))]
[Route("api/test/start")]
public async Task StartTest()
{
DateTime startTime = DateTime.Now;
var testProcessor = new TestAsync();
await testProcessor.StartTestAsync();
HttpStatusCode statusCode = HttpStatusCode.OK;
return Content(statusCode, new TestResult
{
Date = DateTime.Now,
Success = true,
Message = "test"
});
}
}
}
unit test async controller with result check from response
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestAPI.Controllers;
using TestAPI.Models;
using System.Web.Http;
using System.Threading.Tasks;
using System.Net;
using System.Web.Script.Serialization;
namespace Unit.Tests.Controllers
{
///
/// Summary description for ControllerTest
///
[TestClass]
public class ControllerTest
{
private TestController _testController;
[TestInitialize]
public void estAPI_Initializer()
{
_testController = new TestController();
var configuration = new HttpConfiguration();
System.Net.Http.HttpRequestMessage request = new System.Net.Http.HttpRequestMessage();
request.Headers.Add("Authorization", "Bearer 1232141241");
request.Headers.Add("ContentType", "application/json");
_testController.Request = request;
_testController.Configuration = configuration;
}
[TestCategory("Unit test")]
[TestMethod]
public async Task API_Async_Controller_Test()
{
IHttpActionResult asyncResponse = await _testController.StartTest();
var cToken = new System.Threading.CancellationToken(true);
var rResult = asyncResponse.ExecuteAsync(cToken);
Assert.IsNotNull(rResult);
Assert.IsNotNull(rResult.Result);
Assert.AreEqual(rResult.Result.StatusCode, HttpStatusCode.OK);
Assert.IsNotNull(rResult.Result.Content);
var rContent = rResult.Result.Content;
string data = await rContent.ReadAsStringAsync();
Assert.IsNotNull(data);
JavaScriptSerializer JSserializer = new JavaScriptSerializer();
var finalResult = JSserializer.Deserialize(data);
Assert.IsNotNull(finalResult);
Assert.IsTrue(finalResult.Success);
}
}
}