使用GraphQlTester测试时,如何Mock MyClient的返回数据?
正确Mock MyClient并注入到Spring Boot GraphQL测试中的方案
核心思路
利用Spring Boot测试框架提供的@MockBean注解,将容器中实际的MyClient替换为Mockito生成的Mock实例,这样CustomerService调用的就是Mock对象,而非未实现的真实类,从而避免抛出NotImplementedException。
步骤与代码示例
测试类基础配置
- 使用
@SpringBootTest加载Spring上下文,指定webEnvironment = MOCK模拟Web环境 - 通过
@MockBean声明要Mock的MyClient,Spring会自动将该Mock实例注入到依赖它的CustomerService中 - 注入
GraphQlTester用于执行GraphQL查询测试
- 使用
定义Mock方法的返回值
在测试方法中,用Mockito的when()方法指定MyClient目标方法被调用时的模拟返回数据。完整测试代码示例
import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.graphql.test.tester.GraphQlTester; import static org.mockito.Mockito.when; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) public class CustomerControllerTest { @Autowired private GraphQlTester graphQlTester; @MockBean private MyClient myClient; @Test void testCustomerQuery() { // 构造模拟数据并指定MyClient方法的返回值 Customer mockCustomer = new Customer("1", "Alice", "alice@example.com"); when(myClient.getCustomerById("1")).thenReturn(mockCustomer); // 编写GraphQL查询语句 String query = """ query GetCustomer($id: String!) { customer(id: $id) { id name email } } """; // 执行查询并验证返回结果 graphQlTester.document(query) .variable("id", "1") .execute() .path("customer") .matchesJson(""" { "id": "1", "name": "Alice", "email": "alice@example.com" } """); } }
关键注意事项
- 不要使用普通的
@Mock注解,它仅创建Mock对象但不会注入到Spring容器中;@MockBean才会替换容器内的Bean实例,确保CustomerService能获取到Mock的MyClient - 确保
MyClient是Spring管理的Bean(比如标注了@Component或@Service),这样@MockBean才能正确替换它
内容的提问来源于stack exchange,提问作者Ebad
相关产品推荐
相关产品推荐

