mockito 如何在JAX-RS中模拟HttpUrlConnection

h5qlskok  于 2022-11-08  发布在  其他
关注(0)|答案(1)|浏览(314)

我试着为我的班级做一个模拟测试,但它不起作用。
原始类:

public class Service {
  .................
  @POST
  ...
  public Message Info(@NotNull @Valid final UUID Id) throws IOException {
    ............
    String httpLink = Config.getLink();
    ...
    if ( ...) { 
      HttpURLConnection urlConnection = null;
      URL url = new URL(OriginalLink);
      urlConnection = (HttpURLConnection) url.openConnection();
      urlConnection.setDoOutput(true);
      urlConnection.setRequestMethod("GET");
      urlConnection.setUseCaches(false);
      urlConnection.setConnectTimeout(50000);
      urlConnection.setReadTimeout(50000);
      urlConnection.setRequestProperty("Content-Type", "application/json");
      urlConnection.connect();
      .................
      String jsonobject = "..."; //data to be posted into api
      .......
    } else {
      return new Message("No data to posted from file");
    }
    return new Message("successfully posted data from file");
  }
}

测试类别:

@Before
public void before() {
  MockitoAnnotations.initMocks(this);
  URL u = PowerMockito.mock(URL.class);
  String url = "url";
  PowerMockito.whenNew(URL.class).withArguments(url).thenReturn(u);
  HttpURLConnection huc = PowerMockito.mock(HttpURLConnection.class);
  PowerMockito.when(u.openConnection()).thenReturn(huc);
  PowerMockito.when(huc.getResponseCode()).thenReturn(200);
  .....
  PowerMockito.when(Config.getLink())
    .thenReturn("url");
}
 @Test
 public void testInfo() throws IOException {
    ............
    Message org = new Message("successfully posted data from file");
    Message msg = Service.Info(uuid);
    assertEquals(msg,org);
 }

我尝试使用Mockito和PowerMockRunner进行模拟,但没有成功。使用PowerMockito时,我得到“java.lang.NullPointerException”

unhi4e5o

unhi4e5o1#

对于您的实现,您不能模拟HttpURLConnection,因为它是在URL的不可模拟示例中创建的,而该示例是在您的方法中使用new URL(OriginalLink);创建的
您必须创建带有某种工厂的URL,并将其注入到服务中,然后您可以模拟该服务以提供一个模拟的URL示例,而该模拟的URL示例必须提供一个模拟的HttpURLConnection示例。
或者,将创建到URL的连接的部分提取到一个额外的方法中,该方法获取URL并返回连接的HttpURLConnection,然后可以额外测试该方法,并模拟或窥探它,以便测试另一个方法。
比如

class ConnectionService {
  HttpURLConnection openConnection(URL connectTo) {
    HttpURLConnection urlConnection = (HttpURLConnection) connectTo.openConnection();
    urlConnection.setDoOutput(true);
    urlConnection.setRequestMethod("GET");
    urlConnection.setUseCaches(false);
    urlConnection.setConnectTimeout(50000);
    urlConnection.setReadTimeout(50000);
    urlConnection.setRequestProperty("Content-Type", "application/json");
    urlConnection.connect();
    return urlConnection;
  }
}

然后在代码中:

// get connectionService injected
URL url = new URL(OriginalLink);
HttpURLConnection urlConnection = connectionService.openConnection(url);

相关问题