使用Mockito编写Contentstack SDK单元测试:Mock Retrofit2方法遇阻求助
Mock Contentstack SDK中entry.create(prodRequest).execute() 方法(Retrofit2 + Mockito)
核心思路
Contentstack的entry.create(prodRequest)返回的是Retrofit2的Call<T>对象,你需要Mock整个调用链:从Contentstack → Stack → ContentType → Entry → Call,最终让Call.execute()返回预设的Response。
具体实现步骤
Mock所有层级的对象
用Mockito的@Mock注解或Mockito.mock()方法,创建Contentstack、Stack、ContentType、Entry、Call以及Response的Mock实例。构建调用链的Mock逻辑
通过when().thenReturn()定义每个方法调用的返回值,让链式调用最终指向Mock的Call对象,再Mock其execute()方法返回预设响应。处理Final类(如果需要)
Retrofit2的Response和部分Contentstack SDK类可能是Final类,Mockito默认无法Mock,需启用Mockito的Inline Mock Maker。
完整测试代码示例
import com.contentstack.cms.Contentstack; import com.contentstack.cms.stack.Entry; import com.contentstack.cms.stack.Stack; import com.contentstack.cms.stack.ContentType; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import retrofit2.Call; import retrofit2.Response; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import static org.junit.jupiter.api.Assertions.assertTrue; @ExtendWith(MockitoExtension.class) public class EntryCreationTest { // Mock所有依赖对象 @Mock private Contentstack mockContentstack; @Mock private Stack mockStack; @Mock private ContentType mockContentType; @Mock private Entry mockEntry; @Mock private Call<YourResponsePOJO> mockCall; @Mock private Response<YourResponsePOJO> mockResponse; @Test void testEntryCreateSuccess() throws Exception { // 1. 定义Mock调用链 when(mockContentstack.stack(any(String.class), any(String.class))).thenReturn(mockStack); when(mockStack.contentType(any(String.class))).thenReturn(mockContentType); when(mockContentType.entry()).thenReturn(mockEntry); when(mockEntry.create(any(YourRequestPOJO.class))).thenReturn(mockCall); when(mockCall.execute()).thenReturn(mockResponse); when(mockResponse.isSuccessful()).thenReturn(true); // 2. 执行业务代码(示例:假设业务逻辑封装在Service中) YourContentService service = new YourContentService(mockContentstack); boolean isCreated = service.createProductionEntry("test-api-key", "test-token", "test-content-type", new YourRequestPOJO()); // 3. 断言验证 assertTrue(isCreated); } }
关键注意事项
- 替换泛型类型:将
YourRequestPOJO和YourResponsePOJO替换为你实际使用的请求/响应实体类。 - 启用Inline Mock Maker:若遇到
Cannot mock/spy class retrofit2.Response错误,在src/test/resources/mockito-extensions/目录下创建org.mockito.plugins.MockMaker文件,内容为:mock-maker-inline - 参数匹配:如果需要严格匹配
prodRequest,可使用eq(prodRequest)代替any(YourRequestPOJO.class),但需确保请求类正确实现了equals()方法。
内容的提问来源于stack exchange,提问作者user3674968
相关产品推荐
相关产品推荐

