我在服务类中有一个方法来调用外部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来春天。
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
当我们需要引导整个容器时,可以使用@SpringBootTest注释。注释通过创建将在我们的测试中使用的ApplicationContext来工作。
@RunWith(SpringRunner.class)用于提供Spring Boot测试功能和JUnit之间的桥梁。每当我们在JUnit测试中使用任何Spring Boot测试功能时,都需要这个注释。
@MockBean Annotation,可用于向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);
}
}
我建议,你在OkHttpClient
课程中将你的Configuration
实例化为自己的方法。之后你可以在任何需要的地方@Inject
客户端,测试变得更容易,因为你可以@Mock
它。
这就是说Spring
管理的bean:
@Configuration
public class OkHttpClientConfiguration {
@Bean
public OkHttpClient okHttpClient() {
return new OkHttpClient();
}
}
......你的生产课:
@Component
public class ProductionClass {
@Inject
private OkHttpClient okHttpClient;
public string sendMess(EventObj event) {
okHttpClient // whatever you want
[…]
}
}
......和你的考试:
public class SpyTest {
@InjectMocks
private ProductionClass productionClass;
@Mock
private OkHttpClient okHttpClient;
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
@Test
public void spyInsteadOfPowermock() {
Request request = // mock the request
when(okHttpClient.newCall(request)).thenReturn(mock(Call.class));
}
}