Expand my Community achievements bar.

Enhance your AEM Assets & Boost Your Development: [AEM Gems | June 19, 2024] Improving the Developer Experience with New APIs and Events

Stuck in Service IMPL Junit test class

Avatar

Level 3

Dear Team,

 

I have written below test class for my ClientIntegrationDataAPIServiceImpl class as below.

 

But I am getting nullpointer exception for below in my JUNIT Class

String actual = clientIntegrationDataAPIServiceImpl.requestCommunityCreation(clientCommunity);

 

****************** JUNIT CLASS ClientIntegrationDataAPIServiceImplTest********************

package ai.contentadmin.core.service;

import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;

import java.io.IOException;
import java.net.URISyntaxException;

import javax.jcr.RepositoryException;

import org.apache.sling.api.resource.LoginException;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;

import com.github.tomakehurst.wiremock.WireMockServer;

import ai.contentadmin.core.constants.Constants;
import ai.contentadmin.core.models.authorapi.ClientCommunity;
import io.wcm.testing.mock.aem.junit5.AemContext;

class ClientIntegrationDataAPIServiceImplTest {

private WireMockServer wireMockServer = new WireMockServer(wireMockConfig().dynamicPort());

@Rule
public final AemContext context = new AemContext(ResourceResolverType.JCR_MOCK);

@InjectMocks
ClientIntegrationDataAPIServiceImpl clientIntegrationDataAPIServiceImpl;

@test
void requestCommunityCreation() throws IOException, URISyntaxException, LoginException, RepositoryException {
wireMockServer.stubFor(post("/search".concat(String.format(Constants.COMMUNITIES)))
.willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json")));
ClientCommunity clientCommunity = new ClientCommunity();
clientCommunity.setName("TestCommunity");
clientCommunity.setUserId("userid");
clientCommunity.setType("client");
clientCommunity.setPrivate(true);
String expected = Constants.STATUS_OK;
String actual = clientIntegrationDataAPIServiceImpl.requestCommunityCreation(clientCommunity);
Assert.assertEquals("Response should match", expected, actual);
wireMockServer.stop();
}

}

 

------------------------ ClientIntegrationDataAPIService Java Class ----------------------

package ai.contentadmin.core.service;
 
import ai.contentadmin.core.models.authorapi.ClientCommunity;
import org.apache.sling.api.resource.LoginException;
 
import javax.jcr.RepositoryException;
import java.io.IOException;
import java.net.URISyntaxException;
 
/**
 * Service interface for the Content Authoring API client implementation.
 */
public interface ClientIntegrationDataAPIService {
 
 
    String getClientIntegrationDataSuggestions(String field, String value, String path) throws IOException, URISyntaxException, LoginException, RepositoryException;
 
/**
* @Return service name
*/
String getMarcelServiceName();
 
/**
* @Return resturn access key
*/
String getClientIntegrationDataServiceApiAccessKey();
 
/**
* @Return URL
*/
String getUrl();
 
String requestCommunityCreation(ClientCommunity clientcommunity) throws URISyntaxException, IOException;
}
 
-------------------------------- ClientIntegrationDataAPIServiceImpl Class -----------------------------------
   
     @Override
    public String getClientIntegrationDataSuggestions(String field, String value, String path) throws IOException, URISyntaxException, LoginException, RepositoryException {
        String response;
        if(field.startsWith(Constants.COMMUNITIES_BY_TYPE)) {
            String[] fieldSplit = field.split("/");
            field = fieldSplit[0] + "/" + URLEncoder.encode(fieldSplit[1], Constants.UTF8);
            response = getResponse(field, value, path, true);
            // filtering communities dropdown, does not show communities to authors that are already used in other fragments.
            Set<String> communities;
            if (!path.isEmpty()) {
                communities = fetchExistingCommunities(path);
            } else {
                communities = new HashSet<>();
            }
            response = processResponseForCommunities(response, communities);
 
        } else {
            response = getResponse(field, value, path, field.contains("/"));
            if (field.equals(SynapseConstants.CLIENT_AUTHORS)) {
                response = processClientAuthorsResponse(response);
            } else if (field.equals(SynapseConstants.PEOPLE)) {
                response = processCommunityContentManagersResponse(response);
            }
        }
        LOGGER.info("Response: {}", response);
        return StringEscapeUtils.unescapeHtml(response);
    }
 
 
 /**
     * Method that wraps the HttpHeaders required to consume the content authoring API
     * @Return Array of headers to consume the content authoring API
     */
    private Header[] getHeaders(){
        Header[] httpHeaders = new Header[2];
 
        httpHeaders[0] = new BasicHeader(Constants.CLIENT_INTEGRATION_DATA_API_ACCESS_KEY_HEADER_NAME, config.clientIntegrationDataServiceApiAccessKey());
        httpHeaders[1] = new BasicHeader(Constants.HEADER_CONTENT_TYPE, Constants.APPLICATION_JSON);
        return  httpHeaders;
    }
 
    @Override
public String getClientIntegrationDataServiceApiAccessKey() {
return config.clientIntegrationDataServiceApiAccessKey();
}
 
public String getServiceName() {
return config.serviceName();
}
 
public String getUrl() {
return config.getUrl();
}
 
    @Override
    public String requestCommunityCreation(ClientCommunity clientcommunity) throws URISyntaxException, IOException {
        String url = config.getUrl().concat(Constants.COMMUNITIES);
        LOGGER.info("API URL: {}", url);
        HttpPost httpPost = new HttpPost(new URI(url));
        httpPost.setHeaders(getHeaders());
        StringEntity stringEntity = new StringEntity(clientcommunity.toString(), Constants.UTF_8);
        LOGGER.info("Sending the community request [{}]", clientcommunity);
        httpPost.setEntity(stringEntity);
 
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpResponse response = httpClient.execute(httpPost);
        LOGGER.info("Community response [{}]", IOUtils.toString(response.getEntity().getContent(), Constants.UTF_8));
        return response.getStatusLine().getReasonPhrase();
    }
}
 
Please help me here. Thanks in advance
4 Replies

Avatar

Community Advisor

Hi @subnaik 

Based on the code you provided, it seems that the clientIntegrationDataAPIServiceImpl object is not properly initialized in your JUnit test class, which is causing the NullPointerException when you call the requestCommunityCreation method.

To fix this issue, you need to properly initialize the clientIntegrationDataAPIServiceImpl object in your JUnit test class. One way to do this is to use a mocking framework like Mockito to create a mock object of the ClientIntegrationDataAPIServiceImpl class, and then inject this mock object into your test class using the @InjectMocks annotation.

import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;

import java.io.IOException;
import java.net.URISyntaxException;

import javax.jcr.RepositoryException;

import org.apache.sling.api.resource.LoginException;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;

import com.github.tomakehurst.wiremock.WireMockServer;

import ai.contentadmin.core.constants.Constants;
import ai.contentadmin.core.models.authorapi.ClientCommunity;
import io.wcm.testing.mock.aem.junit5.AemContext;

class ClientIntegrationDataAPIServiceImplTest {

    private WireMockServer wireMockServer = new WireMockServer(wireMockConfig().dynamicPort());

    @Rule
    public final AemContext context = new AemContext(ResourceResolverType.JCR_MOCK);

    @Rule
    public MockitoRule mockitoRule = MockitoJUnit.rule();

    @Mock
    private ClientIntegrationDataAPIService clientIntegrationDataAPIService;

    @InjectMocks
    private ClientIntegrationDataAPIServiceImpl clientIntegrationDataAPIServiceImpl;

    @Test
    void requestCommunityCreation() throws IOException, URISyntaxException, LoginException, RepositoryException {
        wireMockServer.stubFor(post("/search".concat(String.format(Constants.COMMUNITIES)))
                .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json")));
        ClientCommunity clientCommunity = new ClientCommunity();
        clientCommunity.setName("TestCommunity");
        clientCommunity.setUserId("userid");
        clientCommunity.setType("client");
        clientCommunity.setPrivate(true);
        String expected = Constants.STATUS_OK;
        Mockito.when(clientIntegrationDataAPIService.requestCommunityCreation(clientCommunity)).thenReturn(expected);
        String actual = clientIntegrationDataAPIServiceImpl.requestCommunityCreation(clientCommunity);
        Assert.assertEquals("Response should match", expected, actual);
        wireMockServer.stop();
    }

}

In this modified test class, we have added the @Mock annotation to create a mock object of the ClientIntegrationDataAPIService interface, and the @InjectMocks annotation to inject this mock object into the clientIntegrationDataAPIServiceImpl object. We have also used the Mockito.when method to mock the requestCommunityCreation method of the ClientIntegrationDataAPIService interface, and return the expected result when this method is called.



Avatar

Level 3

@Raja_Reddy 

 

I had run the script like below, but still I am getting null pointer exception

 

class ClientIntegrationDataAPIServiceImplTest {

    private WireMockServer wireMockServer = new WireMockServer(wireMockConfig().dynamicPort());

    @Mock
    private ClientIntegrationDataAPIService clientIntegrationDataAPIService;

    @InjectMocks
    private ClientIntegrationDataAPIServiceImpl clientIntegrationDataAPIServiceImpl;

    @Test
    void requestCommunityCreation() throws IOException, URISyntaxException, LoginException, RepositoryException {
        wireMockServer.stubFor(post("/search".concat(String.format(Constants.COMMUNITIES)))
                .willReturn(aResponse().withStatus(200).withHeader("Content-Type", "application/json")));
        ClientCommunity clientCommunity = new ClientCommunity();
        clientCommunity.setName("TestCommunity");
        clientCommunity.setUserId("userid");
        clientCommunity.setType("client");
        clientCommunity.setPrivate(true);
        String expected = Constants.STATUS_OK;
        Mockito.when(clientIntegrationDataAPIService.requestCommunityCreation(clientCommunity)).thenReturn(expected);
        String actual = clientIntegrationDataAPIServiceImpl.requestCommunityCreation(clientCommunity);
        Assert.assertEquals("Response should match", expected, actual);
        wireMockServer.stop();
    }

 

Avatar

Community Advisor

The null pointer exception could be caused by several reasons. One possible reason is that the `clientIntegrationDataAPIService` mock object is not properly initialized. You can try adding the `@RunWith(MockitoJUnitRunner.class)` annotation to the test class to initialize the mock objects.

 

 

@RunWith(MockitoJUnitRunner.class)

class ClientIntegrationDataAPIServiceImplTest {

 

    // rest of the code

}

 

If this does not solve the issue, you can provide more information about the exception message and stack trace to help identify the root cause of the problem.



Avatar

Administrator

@subnaik Did you find the suggestion helpful? Please let us know if more information is required. Otherwise, please mark the answer as correct for posterity. If you have found out solution yourself, please share it with the community.



Kautuk Sahni