OpenRasta Unit Testing

I need to start work on the OpenRasta project (xml via http service). OpenRasta looks great, but, unfortunately, working examples seem to be few and far between on the Internet. If you look at the test side of the project, if my handlers return strongly typed objects (not OperationResult), that is:

public class PersonHandler ... public Person Get(int id) { ... 

How can I check http status codes? (For example, if the handler throws an uncaught exception). I'm not sure at what level the tests pass, and what needs to be taunted (using moq btw)

Any help appreciated, especially the encoded examples!

+4
source share
2 answers

I ran into the same problem and ended up writing my tests as integration tests at a much higher level, actually making real REST / HTTP calls through a simple HttpWebRequest client. This allowed me to check the headers / status codes of the HTTP response and double check the serialization of JSON / XML from the client's point of view, which was as important as successful operations.

I started by returning OperationResult from all of my handlers and used them to wrap strongly typed objects. My handlers all inherit from the base class with a few helper methods that make it easy to return a custom error with a convenient error message. The more I encoded this, the more my handlers resembled an ASP.NET MVC controller. eg:.

  public OperationResult GetById(int id) { try { // do stuff here return OKResult( // some strongly-typed resource ); } catch(SomeException ex) { return BadRequestResult(SomeErrorCode, ex.Message); } } 

Then, in the test client, it is quite simple to check the HTTP status code. Obviously, this doesn’t really help make fun. I'm not sure what the best solution is, in fact, I preferred this question in the hope that someone will answer it better than I can, but it has worked for me so far.

+1
source

A handler is just a class - ideally with minimal dependencies - so your unit tests can simply test the isolated logic in the class.

If you want to test status codes, I recommend (based on very little experience!) To use OpenRasta self-service.

Here's a test (slightly modified) that I wrote recently:

  [TestMethod] public void POST_with_inaccurate_contentLength_returns_405() { var resource = GetResource(); IRequest request = new InMemoryRequest { HttpMethod = "POST", Uri = new Uri("http://localhost/Resource"), }; request.Headers.ContentLength = 16; //wrong! request.Entity.Stream.Write(resource.Content, 0, resource.Content.Length); var response = _host.ProcessRequest(request); Assert.AreEqual(405, response.StatusCode); } 

I should add that the host is configured in the TestInitialize method as such:

  _host = new InMemoryHost(new Configuration()); _host.Resolver.AddDependencyInstance(typeof(IFileResourceRepository), _repository, DependencyLifetime.Singleton); 

... and cleared in the TestCleanup method.

+1
source

All Articles