Other than showcasing how monetary quantities can be formatted and showing off the data available for different currencies, one of the objectives of NMoneys.Web is showing code samples on how to accomplish common tasks.
Deviate from Reality
Code examples, like code comments, are always at risk to deviate from reality offered by code, given a forgetful developer fails to change samples and code when software evolves.
Unfortunately, there is no samples (or comments) compiler or tester so far… Or is there?
The Real Thing
What if we could serve .cs source files that get compiled (and, optionally, tested) so that we have totally living documentation?
Serving files with the .cs extension is disabled by default by ASP.NET, but it can be easily enabled and constrained to a path of the application:
So, whenever a source file is requested (for example, from the quickstart), a real .cs file is served.
Real Things Get Compiled
What’s more, those source files that are served through IIS, can be compiled to verify their validity as C# code.
That can be achieved in an automated test and it is simple, although it involves more than one step:
- Add the .cs files that need to be compiled to the test project as links (so that there is no file duplication)
- Set the Build Action to Content
- Set the Copy to Output Directory to Copy Always
And with those steps, every time the test project is compiled, there will be a bunch of .cs files inside a folder hierarchy below the bin folder.
In order to compile them, I chose to use the compilation and code generation services of
CSharpCodeProvider, that can be wrapped in a function in order to call it from multiple tests:
Tests make Wonderful Examples
That I am quite a fan of automated testing, quite a few people can confirm.
I am also a believer that well-written unit tests make one of the best documentations available and I put my money where my mouth was by writing the code samples for my two Codeproject articles I wrote some time ago as unit tests.
So we can compile our code samples, how difficult could it be to run the tests they contain? Not much, to be honest.
- Add references to nunit.core.dll and nunit.core.interfaces.dll (that can be obtained from the NUnit.Runners packages (or from my version of it NUnit.Runners.lite)
- Call this method from multiple tests:
- Assert that are not failures in the result (the
.IsFailure
property)