Question

Mockito unit test cases for QueryResultCallBack() - one of the Query inner class

  • 14 September 2023
  • 3 replies
  • 97 views

I am writing test cases to meet the Sonar coverage for my code and I am not sure how to write test cases for the below piece of code →

I am basically using Query class to fetch details from Cs using java management and am unable to write test cases for the below. 

 

Query query = stack.contentType(CS_TYPE_PRODUCT).query();query = query.where(key, value);

// I am more concerned about the below code to write test coverage 

query.find(new QueryResultsCallBack() {  @Override  public void onCompletion(ResponseType responseType, QueryResult queryresult, Error error) {    if (error == null) {      PcmMetadataAppDto pcmMeta = new PcmMetadataAppDto();      pcmMeta.setPcmEntryLocale(queryresult.getResultObjects().get(0).get("locale").toString());      pcmMeta.setPcmEntryUid(queryresult.getResultObjects().get(0).get("uid").toString());      pcmMeta.setPcmEntryVersion(queryresult.getResultObjects().get(0)          .get("_version").toString());      pcmMetadataResponseAppDto.setPcmMetadata(pcmMeta);      try {        pcmMeta.setPcmEntryUrl(getPcmUri(stackUrl, stackApiKey, CS_TYPE_PRODUCT,            pcmMeta.getPcmEntryLocale(), pcmMeta.getPcmEntryUid()).toString());      } catch (URISyntaxException e) {        throw new RuntimeException(e);      }      log.info("query result is {} ", queryresult.getResultObjects().get(0).getJSONObject(""));    }  }});

 

 


3 replies

@shailesh Mishra Appreciate if you help on this please 🙂

Userlevel 1

Dear Lalatendu,

This is a fully customized approach, and it's entirely up to you how you would like to write tests for it. You can draw inspiration from the code provided below:
 

public interface QueryResultsCallBack {
void onCompletion(ResponseType responseType, QueryResult queryResult, Error error);
}
import org.junit.Test;
import org.mockito.Mockito;

public class QueryResultsCallBackTest {

@Test
public void testQueryResultsCallBack() {
// Create a mock implementation of QueryResultsCallBack
QueryResultsCallBack callBack = Mockito.mock(QueryResultsCallBack.class);

// Define the expected arguments
ResponseType responseType = /* create a mock ResponseType */;
QueryResult queryResult = /* create a mock QueryResult */;
Error error = /* create a mock Error */;

// Simulate the onCompletion method call
callBack.onCompletion(responseType, queryResult, error);

// Verify that the onCompletion method was called with the expected arguments
Mockito.verify(callBack).onCompletion(responseType, queryResult, error);
}
}


A complete sample code:
 

import org.junit.Test;
import org.mockito.Mock;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;

public class YourClassTest {

@Mock
private Stack stack; // Mock the Stack dependency
@Mock
private Query query; // Mock the Query dependency
@Mock
private QueryResult queryResult; // Mock the QueryResult dependency
@Mock
private ResponseType responseType; // Mock the ResponseType dependency
@Mock
private Error error; // Mock the Error dependency (if needed)

@Test
public void testFetchQuery() {
// Initialize the mocks and set up behavior
when(stack.contentType(contentTypeUID)).thenReturn(stack); // Mock the chain calls
when(stack.query()).thenReturn(query);

// Simulate the behavior of the query.find() call
doAnswer(invocation -> {
QueryResultsCallBack callBack = invocation.getArgument(0);

// Simulate a successful query result
callBack.onCompletion(responseType, queryResult, error);

// You can also set up queryResult.getResultObjects() to return a list if needed.

return null;
}).when(query).find(any(QueryResultsCallBack.class));

// Call the method in your class that triggers the asynchronous code
YourClass yourClass = new YourClass(stack); // Create an instance of YourClass with the mocked stack
yourClass.fetchQuery();

// Assert the expected behavior, e.g., check the state of listOfEntries
// and other relevant variables
}
}

Thank you !

@shailesh Mishra Thanks for the response, I will take it as a base and can start working on my requirements. Much appreciated.

Reply