Unit Testing WCMUse Classes using Mockito

05287_Unit-Testing-WCMUse-Classes-using-Mockito
Developers know testing code is important, and one of the best ways to do so is through unit tests. One of the questions preventing developers from writing unit tests, in Adobe Experience Manager development, is the question: how can I start writing tests, when required classes are only available in the context of a running AEM instance, that won’t fail because of a null pointer?

Recently I spent some time trying to answer that question. I found a simple solution, for a simple case that has promise to also cover some more complicated scenarios. The solutions involves using Mockito to mock objects and provide test return values for methods in classes not available outside the context of AEM.

Example WCMUse Class

Example Test Class

Conclusion
Writing tests for WCMUse classes, for the simple example, was easier than I expected. All that needs to be done to set up the test class for testing WCMUse classes is:

  • Create a mockup of the WCMUse class being tested.
  • Create objects used for testing (i.e., properties map).
  • Configure the mock object to do what is needed for the methods used.
    • Return a value needed for the test.
    • Call the actual method.
  • Write the tests.

Here are some references for mocked objects for testing code used in AEM: