BREAKING NEWS: Exadel named a Leader in this Forrester Agile Software Development Service Providers report... Learn more!  

AEM Tip: JUnit Tests for WCMUsePojo Objects

 
 
 

When we develop AEM components, we add some logic into them. This logic can include a variety of source code: helpers, utils, or code designed specially for a component. After developing a number of components, we need to verify the logic. Any refactoring, any changes in helper and util classes, requires us to validate existing source code, thus verifying that the code is in the expected state. JUnit tests help us do this.

However, in the process of developing the JUnit tests, a few issues arose. For instance: WCMUsePojo (a base class for components) has many static methods which have to be mocked to perform testing. We have to load content and test our component against this content to validate its logic.

For our unit tests, we use an open source project called wcm.io as well as PowerMock. Wcm.io provides various useful AEM mock objects. PowerMock helps to override static and final methods in classes for mocking. PowerMock takes precedence over the Mockito framework in this process.

Let’s imagine that this is our component class:

To write a unit test for a class, the first thing we will do is annotate a test class with the following annotations:

@RunWith specifies a runner for JUnit; @PrepareForTest lists a number of classes which have final or static methods to mock.

Here is the component base class:

AemContext is a useful mock object. It could contain test content.  Here is a document describing how to load it.

Next we can get ResourceResolver.

And mock it for further use while testing in a component:

In the base class we mock our test component:

Now all its methods are mocked. To call a real method to test it, we would write:

If a test method is private and we have to test it or call it, we can write:

How to mock a static method?

For instance, let’s say we have a util class with a static method which is used in our component:

In a unit test we would write:

PowerMockito.mockStatic mocks all the methods in a specified class. If you want to mock one method, use PowerMockito.spy.

Source Code

1. Component Class

2. Base Test Class

3. JUnit Test Class

4. Test Page Content [TestNode.json]

 

NEW! Want to test new technologies like blockchain, AI, mobile, chatbot, and machine learning models? Learn about our Innovation Lab.