You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot JUnit测试Mockito Mock对象返回null值问题咨询

问题原因

你用到的@Mock注解生成的是Mockito模拟对象,默认所有非void方法的返回值都是null,你没有提前指定模拟方法的返回值(也就是打桩),所以调用apiConfiguration.getApiUrl()和restTemplate.getForObject()都会返回null。

修复方案
  • 第一步:给APIConfiguration的getApiUrl()方法打桩,指定测试用的接口域名
  • 第二步:构造测试用的模拟Posts返回数据,给RestTemplate的getForObject()方法打桩,指定调用该方法时返回你构造的模拟数据
  • (可选)如果需要验证方法调用逻辑,可以加Mockito的verify校验

修改后的测试代码示例:

import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;

@Test
void canGetBlogPosts() throws ExecutionException, InterruptedException {
    // 1. 构造测试模拟数据
    Posts mockPosts = new Posts();
    // 可根据测试需要给mockPosts添加测试Post对象,示例:
    // Post testPost = new Post();
    // testPost.setId(1L);
    // testPost.setLikes(100);
    // mockPosts.addPost(testPost);

    // 2. 给模拟对象打桩,指定返回值
    String testApiUrl = "https://test.hatchways.io/api/posts";
    when(apiConfiguration.getApiUrl()).thenReturn(testApiUrl);
    String expectedUrl = testApiUrl + "/?tag=science";
    when(restTemplate.getForObject(eq(expectedUrl), eq(Posts.class))).thenReturn(mockPosts);

    // 3. 调用测试方法
    System.out.println(apiConfiguration.getApiUrl()); // 此时会输出你设置的testApiUrl
    CompletableFuture<Posts> posts = underTest.getBlogPostWithOneTag("science");
    System.out.println(posts.get()); // 此时会输出你构造的mockPosts
    // 可增加断言校验结果
    assertNotNull(posts.get());
}

注意事项

  • 如果不需要精确匹配请求url,可以把getForObject的第一个参数换成anyString(),适配任意url的调用
  • 你当前的测试是纯Mockito单元测试,没有启动Spring上下文,所以@Async注解不会生效,方法会同步执行,不需要额外处理异步逻辑
  • 如果需要测试异步逻辑,需要使用@SpringBootTest启动Spring上下文,同时加上@EnableAsync注解开启异步支持

内容的提问来源于stack exchange,提问作者srachoor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 21:45:03