Last active
June 24, 2016 09:55
-
-
Save janhebnes/6e007070918fd8cec8e77e24d5abd647 to your computer and use it in GitHub Desktop.
Sample Unit test looking at a Controller returning the WebAPI 2 pattern IHttpActionResult for reference.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[TestMethod] | |
public void Study_DatetimeOffsets_in_DayViewModel() | |
{ | |
// http://www.asp.net/web-api/overview/testing-and-debugging/unit-testing-controllers-in-web-api | |
// The controller is returning IHttpActionResult, so look at the sample in the bottom of the ms article. | |
// Using OkNegotiatedContentResult safecast resulted in a null in my case. | |
var controller = new DayController(); | |
controller.Request = new HttpRequestMessage(); | |
controller.Configuration = new HttpConfiguration(); | |
IHttpActionResult actionResult = controller.Get("15D8F055-F8A7-40B0-82ED-540B6EF0CC03", new DateTime(2015, 5, 1)); | |
Assert.IsNotNull(actionResult); | |
//var contentResult = actionResult as OkNegotiatedContentResult<IEnumerable<DayViewModel>>; | |
//Assert.IsNotNull(contentResult); // resulted in null | |
// initializing the httpResponseMessage Task and using TryGetContentValue solved it... | |
var httpResponseMessage = httpActionResult.ExecuteAsync(new CancellationToken()).GetAwaiter().GetResult(); //To properly re-throw an exception: http://stackoverflow.com/questions/20170527/how-to-correctly-rethrow-an-exception-of-task-already-in-faulted-state | |
Assert.IsNotNull(httpResponseMessage); | |
Assert.IsTrue(httpResponseMessage.IsSuccessStatusCode); | |
IEnumerable<DayViewModel> dayViewModels; | |
Assert.IsTrue(httpResponseMessage.TryGetContentValue<IEnumerable<DayViewModel>>(out dayViewModels)); | |
Assert.IsNotNull(dayViewModels); | |
var result = dayViewModels.FirstOrDefault(); | |
Assert.IsNotNull(result); | |
Assert.IsTrue(result.response.Success); | |
Assert.IsNotNull(result.production.Count > 0); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment