java - 调用okhttp3的测试方法

标签 java unit-testing spring-boot mocking okhttp

我在服务类中有一个调用外部 API 的方法。我将如何模拟这个 okHttpClient 调用?我曾尝试使用 mockito 这样做,但没有成功。

//this is the format of the method that i want to test
public string sendMess(EventObj event) {
    OkHttpClient client = new OkHttpClient();
    //build payload using the information stored in the payload object
    ResponseBody body = 
        RequestBody.create(MediaType.parse("application/json"), payload);
    Request request = //built using the Requestbody
    //trying to mock a response from execute
    Response response = client.newCall(request).execute();
    //other logic
}

如果有助于测试,我愿意重构服务类。任何建议和建议表示赞赏。谢谢。

最佳答案

因为您使用的是 spring-boot,所以请将 bean 管理留给 spring。

1) 首先创建 OkHttpClient 作为 spring bean 以便你可以在整个应用程序中使用它

@Configuration
public class Config {

@Bean
public OkHttpClient okHttpClient() {
    return new OkHttpClient();
    }
 }

2) 然后在服务类@Autowire OkHttpClient 中使用

@Service
public class SendMsgService {

@Autowired
private OkHttpClient okHttpClient;

 public string sendMess(EventObj event) {

ResponseBody body =  RequestBody.create(MediaType.parse("application/json"), payload);
Request request = //built using the Requestbody
//trying to mock a response from execute
Response response = okHttpClient.newCall(request).execute();
//other logic
   }
 }

测试

3) 现在在测试类中使用@SpringBootTest@RunWith(SpringRunner.class)@MockBean

The @SpringBootTest annotation can be used when we need to bootstrap the entire container. The annotation works by creating the ApplicationContext that will be utilized in our tests.

@RunWith(SpringRunner.class) is used to provide a bridge between Spring Boot test features and JUnit. Whenever we are using any Spring Boot testing features in out JUnit tests, this annotation will be required.

@MockBean Annotation that can be used to add mocks to a Spring ApplicationContext.

@SpringBootTest
@RunWith(SpringRunner.class)
public class ServiceTest {

 @Autowire
 private SendMsgService sendMsgService;

 @MockBean
 private OkHttpClient okHttpClient;

  @Test
  public void testSendMsg(){

 given(this.okHttpClient.newCall(ArgumentMatchers.any())
            .execute()).willReturn(String);

  EventObj event = //event object
 String result = sendMsgService.sendMess(event);

  }
 }

关于java - 调用okhttp3的测试方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55345456/

相关文章:

java - 如何编译一个任意命名与公共(public)类名不同的.java文件

Java EE 7 - 注入(inject) Runnable/Callable 对象

c# - 单元测试 - 模拟的一些困难

java - Gradle 和 Spring-bootRun 找不到我的类(class)

java - 使用 thymeleaf 将整数中的分值转换为 HTML 中的货币

java - 记录 JdbcTemplate 查询执行时间

java - java 中的组合框无法正常工作 bluej

unit-testing - Mocha/Karma - 如何测试 CSS 属性

python-3.x - 如何使用带有 Pytest 参数化副作用的补丁进行单元测试?

java - 如何使用本地系统上运行的 Spring Boot 应用程序连接到 AWS 上的 DynamoDB?