Expand my Community achievements bar.

Junits for sling model classes in AEM 6.3

Avatar

Level 8

Hi All,

I have a sling model class, with four different dialog properties that I have as below. For example :

@Inject

    @Optional

    @Via("resource")

    private String videoType;

@Inject

    @Optional

    @Via("resource")

    private String videoId;

and similarly for the other 2 properties

private String videoUrl = StringUtils.EMPTY;

@PostConstruct

    public void init() {

videoUrl = Utility.getVideoUrl(videoType, videoId);

}

public String getVideoUrl() {

        return videoUrl;

    }

The utility class is as below :

    String videoUrl = StringUtils.EMPTY;

        if (videoType != null && id != null) {

            if (videoType.equals("youtube")) {

                videoUrl = Constants.youtube_link + id;

            } else {

                videoUrl = Constants.streamsite + id;

            }

        }

        return videoUrl;

    }

I need to write Junit classes for this utility method and model class. Went through multiple links and codes. but not able to get started on this.

If someone can tell me how to write Junit classes for this, would be really really helpful.

7 Replies

Avatar

Level 8

Hi All,

Any thoughts/code-snippet on this will be helpful.

Avatar

Level 10

We have a GEMS session on testing AEM code that you may find helpful --

From Unit Testing to Integration Test of an AEM Application

Avatar

Level 8

Hi Scott/All,

Thank you for your reply.

Went through, but not quite getting it. Will go over it again.

Since this model class is having just a few lines of code, If someone can provide some sort of snippet on how things have to be written w.r.t this, would be really really helpful

Avatar

Level 10

Look at the default files that a Maven 10 archetype produces - there is a unit testing example --

Adobe Experience Manager Help | Creating your first Adobe Experience Manager 6.2 Project using Adobe...

Look at TestHelloWorldModel

Avatar

Level 8

Hi Scott/ektaa5198549,

Thank you for sharing across the links.

Avatar

Community Advisor

Hello @cquser1,

With unit testing for your AEM application using JUnit4, you can utilise AEM Mocks library.

For example, as you are trying to mock the value returned by the @ValueMapValue annotation, you will need to build the context of an adaptable object. Once that adaptable object is constructed, you can adapt that adaptable object to the Sling Model (underTest). Also mocking the currentPage @ScriptVariable object can be done as easy as a simple line of code; @Mock private Page currentPage.

This seems like a mouthful. Take a look at this reference on how to write JUnit4 unit tests for sling models. This article provides code snippets and examples. 

https://sourcedcode.com/aem-sling-models-unit-test-junit-4-with-examples