Expand my Community achievements bar.

SOLVED

my JUNIT for my service IMPL class is not working.

Avatar

Level 4

Dear All,

 

I have written the below JUNIT for my service IMPL and I am getting null pointer exception for below

 

clientIntegrationDataAPIServiceImpl.requestCommunityCreation(clientCommunity);

 

********************************** JUNIT Class ***************************

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();
}

}

 

********************************** My Service 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 getServiceName();
 
/**
* @Return resturn access key
*/
String getClientIntegrationDataServiceApiAccessKey();
 
/**
* @Return URL
*/
String getUrl();
 
String requestCommunityCreation(ClientCommunity clientcommunity) throws URISyntaxException, IOException;
}
 
*******************************MY Service IMPL*************************
     @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();
    }
}
 
Topics

Topics help categorize Community content and increase your ability to discover relevant content.

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

HI @subnaik ,

You need to register your core service class in test class.

@BeforeEach
    public void setup() throws LoginException {            
        context.registerService(SampleService.class);     
        context.load().json("/sample.json", "/content");
    }

 Here I have mentioned sample service class, you can replace it with your actual service class.


Thanks
Tarun 

View solution in original post

1 Reply

Avatar

Correct answer by
Community Advisor

HI @subnaik ,

You need to register your core service class in test class.

@BeforeEach
    public void setup() throws LoginException {            
        context.registerService(SampleService.class);     
        context.load().json("/sample.json", "/content");
    }

 Here I have mentioned sample service class, you can replace it with your actual service class.


Thanks
Tarun