This page aims at understanding the difficulties that we encounter while unit testing web site project. Details included in this page are intended for beginner level programmers and it is assumed that the reader has ground level knowledge on unit testing.
Visual Studio makes the developer's life easy, in fact lazy by introducing "click to go" features, creating test method is one such cool feature. Now the question is "Is it possible to use VS create test method option for custom class methods in website project?". If you haven't tried this, the answer is a NO. Though VS creates test methods using a bunch of test attributes like testmethod, hosttype, UrlToTest... it can't refer to the classes declared in App_code folder. Let's see how to get rid of this problem.
For a developer, the decision of making a web site as a web application project or a web site project plays a vital role. Both of these options follow a different strategy during execution. But what makes the class methods inside App_Code folder in web site project to be treated as special?
"Web application project compilation generates a DLL in Bin folder, whereas in case of web site project, there wont be any DLL generation."
After reading the above statement, you must have understood the reason behind our problem. Yes, your guess is correct, since there is no DLL generated for the classes in App_Code folder, Visual Studio can't refer to those class names from the unit test project.
Apart from normal class methods, even the web service methods definitions are often placed inside App_Code folder. In such situations, it is very essential to unit test the business logic written for custom classes and web service methods.
Though the solution for this problem is simple, it is non-trivial and a must learn concept. Follow the below steps to resolve this problem.
- Right click the web site project and click on 'publish web site' .
- Give the target location as one of your folders in hard-drive and click on Ok.
- Create a new test project in the solution and try to add reference to the test project.
- In the reference dialog box, go to the path given in step-2 and select App_Code.dll.
- Voila, that's it!! From your test project, now you can refer to all the classes present inside App_code folder.
- From here on, the traditional test method creation steps follows.
I am leaving the remaining steps to the reader as the rest of the process is trivial to the current context.
Points of Interest
App_Code folder in web site project is not a simple folder, it has got special importance in ASP.NET. The code inside this folder is compiled at site run time. Hence any file inside App_Code can be replaced in production server without pre-compilation.
It is worth noting that for this very same reason, App_Code folder is not available for web application project type as it would cause conflicts (compile time DLL and run time DLL).