We are have recently extended the functionality of the Ministry Test Support libraries. The Wiki provides more detail on the capabilities of these supporting libraries. In a previous article, I explained how the Test Support libraries could help test routes in MVC. This feature has now been extended to include testing Web API routes.
Testing Routes in Web API
Ministry.TestingSupport offers a simple solution to make route testing really clean and simple with 2 alternate syntactical approaches. This is achieved through the use of two classes. The first is the 'WebApiRouteAsserter', an instance of which is provided by the ISupportFactoryWithMocks implementation for your chosen testing framework and maintains syntactical similarity with the existing method of MVC route testing. Moq is required for this to work at the moment but if you would like this for your chosen mocking framework feel free to join the project and add support or raise an issue and I'll add support when I can.
The second method is not specific to a mocking framework. The RouteTestingHelper class in the Ministry.TestSupport.WebApi namespace exposes overloaded extension methods to string to test simple Web API routes.
Using the Simple Method
Creating quick Web API Route tests is very simple indeed. Simple create a test class and add a using statement for 'Ministry.TestSupport.WebApi' to allow the string extension methods to become active. You can then write simple tests like this...
Using The WebApiRouteAsserter
This is a straightforward class which simply takes an instance of IAssertionFramework and then wraps up a suite of assertions you would normally perform to test a route into one simple assertion. This follows the same structure as standard MVC route testing. Assertions provided include...
Creating a route test is very straightforward. By inheriting from WebApiRouteTestBase, you get shorthand local assertion methods that call through to the WebApiRouteAsserter. There are some key things to do to set up a route test for your application, as follows...
- Override the 'TestSupportFactory' property with the implementation for your testing framework of choice with mocks.
- Override 'ApiRoutesRegisterFunction' to return the Register method from the WebApiConfig class. This needs to be passed around; it replaces the 'Routes' element used before.
The libraries are available now on nuget, just search for Ministry.TestSupport and Ministry.TestSupport.Moq. The source code, as always, is available on Bitbucket.