Solved

Mockito Junit test cases (Java) for Contentstack Management SDK

  • 31 August 2023
  • 2 replies
  • 100 views

I am writing the below code using Contentstack Management SDK, and when I am writing the unit tests using Mockito framework, not able to Mock the entry.create(prodRequest).execute().

Appreciate if we could get some assistance on this please, (basically how to mock the retrofit2). Here is the code snippet.

import com.contentstack.cms.Contentstack;
import com.contentstack.cms.stack.Entry;
import com.contentstack.cms.stack.Stack;
import retrofit2.Response;
Contentstack contentstack = new Contentstack.Builder().build();
Stack stack = contentstack.stack(stackApiKey, managementToken);
Entry entry = stack.contentType(contentType).entry();
try {
Response responseFromCs = entry.create(prodRequest).execute();
if (responseFromCs.isSuccessful()) {
}

icon

Best answer by lalatendu 7 September 2023, 02:01

View original

2 replies

Userlevel 1

Hi @lalatendu,

To mock functions for unit testing in the Contentstack Java SDK using the Mockito framework, here's a step-by-step explanation along with an example:

1- Add the following dependency to your pom.xml file

<dependency> 
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.12.4</version>
<scope>test</scope>
</dependency>

2. Import Mockito : Make sure you have the Mockito framework added as a dependency to your project.

3. Create a Test Class : Create a test class for the code snippet. The class name should
be ContentstackTest

4. Import the following classes

import com.contentstack.cms.Contentstack;
import com.contentstack.cms.stack.Entry;
import com.contentstack.cms.stack.Stack;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.Mockito;

5. Create a mock object for the Contentstack class

@Mock
private Contentstack contentstack;

6. Create a mock object for the Stack class

@Mock
private Stack stack;

7. Create a mock object for the Entry class.

@Mock
private Entry entry;

8. Configure the mock objects.

Mockito.when(contentstack.stack("apiKey", "managementToken")).thenReturn(stack);
Mockito.when(stack.contentType("contentType")).thenReturn(entry);

9. Write the unit test

@Test
public void testCreateEntry() {
// Arrange
String request = "request";

// Act
Response response = entry.create(request).execute();

// Assert
Mockito.verify(entry).create(request);
Mockito.verify(response).isSuccessful();
}

Run the unit test.

See in detail how you can mock your tests. https://site.mockito.org/

@shailesh Mishra Hey Shailesh , thank you for sharing the details. I am glad that it worked for me and I am able to proceed with your valuable inputs. Thanks a ton for your tmely help 🙂

Reply