Adding unit tests to existing code

A common scenario is to have a set of existing web parts that have no unit tests. The “Approvals” approach to verifying existing output is useful here. Assuming that an existing web part is in a known working state, a test class can be generated very simply using the approach described above. Whatever output is being produced by the web part can simply be made the expected result by renaming the .actual file to replace the .expected file. In this way a simple regression test is created. Refactoring can now be carried out knowing that the functionality of the web part can be quickly verified.

Usually, when working on existing code, there will be a SharePoint site already in existence, either for integration testing or as part of the production system. This site, possibly after copying and simplification, can be used as the reference site to derive the CAML file used by FakePoint.

Care needs to be taken, particularly when retro-adding web part unit tests, to ensure that all the test classes and artefacts are included in source control. It is quite easy to omit the .expected test verification files or any manifest file used by the fake SharePoint objects. To verify this, the entire solution, including the test project, should be restored from source control on a clean machine with Visual Studio installed. The complete solution should then be able to build and run its unit tests.

There may be occasions where, by its nature, it is almost impossible to devise a unit test for an existing WebPart. Although in the ideal case we would like to be able to build a unit test without making any changes to the production code, sometimes a reasonable compromise is to extend the capabilities of the WebPart. For example, suppose we have a WebPart that is designed to render an RSS is feed. On the face of it this WebPart is dependent on having access to an external server to supply the RSS content, and any test built against this WebPart would by definition be an integration test.

You would expect such a WebPart to have a property to allow the user or content editor to specify the RSS source. A reasonable extension would be to include, in addition to the HTTP protocol, the ability to add a file reference. The modified WebPart can now be subjected to a proper unit test by setting the value of the source property to a file, test.rss say, which can be source controlled along with the other test support files.

Last edited Jan 20, 2010 at 7:50 PM by SPDoctor, version 3


No comments yet.