des*_*est 4 java unit-testing mocking okhttp spring-boot
我在服务类中有一个方法可以调用外部 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
}
Run Code Online (Sandbox Code Playgroud)
如果有助于测试,我愿意重构服务类。如有任何建议和推荐,我们将不胜感激。谢谢。
由于您使用的spring-boot是离开管理豆子来春天。
1)首先创建OkHttpClient为 spring bean,以便您可以在整个应用程序中使用它
@Configuration
public class Config {
@Bean
public OkHttpClient okHttpClient() {
return new OkHttpClient();
}
}
Run Code Online (Sandbox Code Playgroud)
2)然后在service类中@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
}
}
Run Code Online (Sandbox Code Playgroud)
测试
3) 现在在测试类中使用@SpringBootTest,@RunWith(SpringRunner.class)和@MockBean
当我们需要引导整个容器时,可以使用@SpringBootTest注解。该注释通过创建将在我们的测试中使用的 ApplicationContext 来工作。
@RunWith(SpringRunner.class) 用于在 Spring Boot 测试功能和 JUnit 之间提供桥梁。每当我们在 JUnit 测试中使用任何 Spring Boot 测试功能时,都需要此注释。
@MockBean 注解,可用于向 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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8374 次 |
| 最近记录: |