How to set runmodes for the sling servlet unit test - Junit5? | Community
Skip to main content
Level 2
Apr 22, 2021 8:13 PM UTC
Solved

How to set runmodes for the sling servlet unit test - Junit5?

I'm using SlingSettingsService to get runmides in the sling servlet. 

 

Any idea how to set runmodes in the test file uisng Junit5 so the servlet could read them when you run doGet(req, res) test?

 

Thanks,

Eugene 

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Ravi_Pampana
Ravi_PampanaAccepted solution
New Participant
Apr 22, 2021 9:26 PM UTC

Hi,

 

We can use below code to set the run modes

 

@Mock

private SlingSettingsService settingsService;

 

Register the service

context.registerService(SlingSettingsService.class, settingsService);

 

Then set the runmodes required for the test cases as below

 

        Set<String> runModes = new HashSet<>();

        runModes.add("author");

        when(settingsService.getRunModes()).thenReturn(runModes);

 

Hope this helps!

 

 

3 replies

EugeneF1Author
Level 2
Apr 23, 2021 6:34 PM UTC

I've come up with the working solution 🙂

Runmodes are passed to the servlet. Here's the example:

 

private DataUpdate servlet;
@Mock
private MockSlingHttpServletRequest req;
@Mock
private SlingSettingsService settingsService;
@Mock
private SlingSettingsService settingsService;

@BeforeEach
void setUp() {
servlet = context.registerInjectActivateService(new DataUpdate());
}
@Test
void doGet() throws ServletException, IOException {
context.runMode("author");
req = context.request();
res = context.response();
servlet.doGet(req, res);
}

 

Translate
Ravi_Pampana
Ravi_PampanaAccepted solution
New Participant
Apr 22, 2021 9:26 PM UTC

Hi,

 

We can use below code to set the run modes

 

@Mock

private SlingSettingsService settingsService;

 

Register the service

context.registerService(SlingSettingsService.class, settingsService);

 

Then set the runmodes required for the test cases as below

 

        Set<String> runModes = new HashSet<>();

        runModes.add("author");

        when(settingsService.getRunModes()).thenReturn(runModes);

 

Hope this helps!

 

 

Translate
EugeneF1Author
Level 2
Apr 23, 2021 6:21 PM UTC
Your code didn't work for me. I was getting Nullpointer on context.registerService(SlingSettingsService.class,settingsService);
Translate