Junits for sling model classes in AEM 6.3

cquser1

25-07-2017

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.

Accepted Solutions (0)

Answers (7)

Answers (7)

Briankasingli

MVP

18-12-2019

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

cquser1

25-07-2017

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