Recently, we had to use a lot of conditional execution of our codes.
The situation was such:
1. In a ASP.Net MVC 3 Unit test project we had to read some variables from the static application bag.
2. Even though we cud inject into and read from the Session Bag, we couldn’t find a easy way for the Application.
3. Using a Mock framework would have been the right solution, but we didn’t have the time to introduce a mocking framework into the solution.
4. From our experience of using the Pre-processor directive, “# if DEBUG” earlier, we thought of depending on the other BUILD CONFIGURATIONS for the same effect. Such that when we run the UNIT TESTS, with a TEST Config, it should return back a fixed value instead of trying to read from the Application Bag.
5. It wasn’t easy, not much help online either, most advocated using the #define statement at the beginning of the class, which was impractical, since it would require recompile to shift between the different configurations.
Without further ado, lets step through the steps which we took to achieve this.
0. Create a Test Solution.
- Add 2 Projects. A Windows Project and a class library.
- The Windows App Project contains a form, with a Button and a text box.
- The Class Library, mimics a Utility project which will lookup from Application or other Cache values and will be called from all other layers.
- Name the Class Library Project, as Common. Add a class Factory, which has a static property, MyProperty, which returns an int.
- On the Button Click event of the Form call the Factory.MyProperty. Display the value in the Text box
1. Create a new Build Configuration Item for the Unit Tests.
- Click on the Configuration Manager, from the Menu
- From the “Active Solution Configurations” combo, Select New…
- Add a new Config, lets say UNITTEST, From the “Copy Settings From” combo, select appropriate config, lets select Debug
- For Both the Projects set the Build Configuration as “UNITTEST”
- Open the Property Page for the “Common” Project and click on the “Build” Tab
- From the “Configurations” combo, select, “UNITTEST”
- In the “Conditional Compilation symbols” textbox, enter “UNITTEST”
- Now add the conditional statement targeting the Build Configurations into the Factory Class
- We are done. Now the breakpoint will enter the # if UNITTEST section, when when the app is run with “UNITTEST” Build Configuration. Costly exercise of writing Mocking framework averted!
- ***Remember, the daily build must not use this configuration, while pushing the binaries to the test environments!