I Like ASP.NET Web Pages–Part II
Continuing from Part I, here are more fun – using .NET 4 dynamic.
- Extension methods for creating dynamic objects
- Validation of dynamic objects (declarative / DSL style)
- Unit Testing within web site
- Mock, stub, fake all in one
Extension methods for creating dynamic objects
To create DTO from database and/or screen (html form), I developed two extension methods.
They made it very easy to create DTO in model.
From the controller, this is how to let the model create a new DTO from screen and save it to database.
The convention here is, table column name = object property name = html input name. And they are case sensitive.
Validation of dynamic objects
Since the DTO is dynamic object, there are no re-defined class to use metadata attributes (data annotations). I think it’s a good thing. It gives me a chance to do validation declaratively. The example below is self-explanatory enough because of its declarative style. It looks like I invented a validation DSL.
Unit Testing
One limitation of web sites is that you cannot create a unit test project and reference to the web site to test classes in the web site. I created in the Rabbit Framework a Testing Module. It provides a familiar way of writing unit tests using TestClass, TestMethod attributes, and an Assert class.
It also has a test runner page.
The test runner page is REST/MVC style. It has URL patterns below.
~/Test the entry page to unit testing
~/Test/All lists all test classes and test methods
~/Test/TestClass runs test methods within the test class
~/Test/TestClass/TestMethod runs a test method within the test class
Mock, stub, fake all in one
Mocking an interface is difficult. It requires emitting classes dynamically, like what Moq does. Mocking a concrete class is more difficult.
Mocking using dynamic object is very easy. The Mock class in Rabbit Framework probably is the world’s simplest mock implementation. 160 Lines in total. No dependency to any 3rd party library.
The Mock class is derived from the DynamicObject. It allows to,
- Verify the sequence of methods to be called
- Verify the times of methods to be called
- Verify the parameter count being passed to methods
- Verify each parameter’s type being passed to methods
- Verify each parameter’s value being passed to methods
I really enjoyed running unit tests with mocking feature on a web page especially with the auto refresh tool.
Add comment February 22nd, 2011