用okhttp3调用的测试方法

问题描述 投票:1回答:2

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

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

java unit-testing spring-boot mocking okhttp3
2个回答
1
投票

因为你正在使用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);

  }
 }

0
投票

我建议,你在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));
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.