asp.net web api - Unit testing a custom Web API MediaTypeFormatter -


i have extended jsonmediatypeformatter in order generate "root" objects in json types decorated custom attribute.

how unit test formatter? interested in how check writetostreamasync(..) method.

the free o'reilly ebook designing evolvable web apis asp.net has useful, specific advice on how test mediatypeformatter.

here test method writetostreamasync. (this approach take test webapicontrib.formatters.xlsx , 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()); 

things note:

  • fakecontent , faketransport fakes of httpcontent , transportcontext classes respectively, code can find in article.
  • task.wait used block execution until task returned writetostreamasync finishes.
  • the output of formatter written memorystream, can read , parsed suitable formatter/deserialiser can make test assertions.

alternatively, write sample controller implementation, start running , test using client call controller methods. chris missal in webapicontrib.formatting.bson.

the controller doesn't need complicated:

public class testcontroller : apicontroller {     public item get(int id)     {         return new item { id = id };     }     // ... } 

set server , 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 tests, call methods on client , want result:

var response = _client.getasync("test/1").result; var result = response.content.readasasync<item>(new hashset<mediatypeformatter> {new testmediatypeformatter()}).result; 

Comments

Popular posts from this blog

assembly - 8086 TASM: Illegal Indexing Mode -

Java, LWJGL, OpenGL 1.1, decoding BufferedImage to Bytebuffer and binding to OpenGL across classes -

javascript - addthis share facebook and google+ url -