Free O'Reilly Version Developing the Evolvable Web API using ASP.NET provides some useful tips on how to test MediaTypeFormatter .
Here is their test method for WriteToStreamAsync . (This is the approach I take for test WebApiContrib.Formatters.Xlsx , and it works well.)
var ms = new MemoryStream(); var content = new FakeContent(); content.Headers.ContentType = new MediaTypeHeaderValue("application/atom+xml"); var formatter = new SyndicationMediaTypeFormatter(); var task = formatter.WriteToStreamAsync(typeof(List<ItemToSerialize>), new List<ItemToSerialize> { new ItemToSerialize { ItemName = "Test" }}, ms, content, new FakeTransport() ); task.Wait(); ms.Seek(0, SeekOrigin.Begin); var atomFormatter = new Atom10FeedFormatter(); atomFormatter.ReadFrom(XmlReader.Create(ms)); Assert.Equal(1, atomFormatter.Feed.Items.Count());
Notes:
FakeContent and FakeTransport are fakes of the HttpContent and TransportContext classes, respectively, the code that you can find in the article.Task.Wait used to block execution until the task returned by WriteToStreamAsync .- The formatting result is written to a
MemoryStream , which can then be read and analyzed by a suitable formatting / deserializer so you can make test statements.
Alternatively, you can write an example implementation of the controller, run it and test it with the client to call the controller methods. This is what Chris Missal does in WebApiContrib.Formatting.Bson .
The controller does not have to be complicated:
public class TestController : ApiController { public Item Get(int id) { return new Item { ID = id }; }
Configure the server and client:
[TestFixtureSetUp] public void fixture_init() { var config = new HttpConfiguration(); config.Formatters.Add(new TestMediaTypeFormatter()); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "{controller}/{id}", defaults: new {id = RouteParameter.Optional} ); var server = new HttpServer(config); _client = new HttpClient(server); _client.BaseAddress = new Uri("http://www.test.com/"); _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson")); }
Now, in your tests, call the methods on the client and do what you want with the result:
var response = _client.GetAsync("test/1").Result; var result = response.Content.ReadAsAsync<Item>(new HashSet<MediaTypeFormatter> {new TestMediaTypeFormatter()}).Result;
source share