我在服务类中有一个调用外部 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/