简体   繁体   中英

Mockito JUnit Testing POST files

I am struggling to write test(s) for the following post method (junit/mockito)

POST method

public JSONObject post(final String url, final Map<String, File> fileMap) {

    final OkHttpClient client = OkHttpClientSingleton.getInstance();
    final MultipartBody.Builder builder = new MultipartBody.Builder()
            .setType(MultipartBody.FORM);

    try {
        for (final Map.Entry entry : fileMap.entrySet()) {
            final String contentType;
            final Path path = Paths.get(((File) entry.getValue()).getAbsolutePath());
            contentType = Files.probeContentType(path);
            final MediaType FILE_MEDIA_TYPE = MediaType.parse(contentType);
            builder.addFormDataPart((String) entry.getKey(), ((File) entry.getValue()).getName(), RequestBody.create(FILE_MEDIA_TYPE, (File) entry.getValue()));

        }
    } catch (final IOException e) {
        e.printStackTrace();
        return null;
    }

    final RequestBody requestBody = builder.build();
    final Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();

    return execute(client, request);

}

and the execute method looks like:

private JSONObject execute(final OkHttpClient client, final Request request) {
    try {
        final Response response = client.newCall(request).execute();
        final String str = Objects.requireNonNull(response.body()).string();
        return new JSONObject(str);
    } catch (final IOException e) {
        e.printStackTrace();
    }
    return buildErrorResponse("Unable to execute request");
}

I have no "fields" to create mocks for (my usual MO!), any tips muchappreciated. I can force an error easily enough but to test full flow at least until the POST

You can mock the web application that receives the post and verify that the correct data is send. Eg you can use http://mock-server.com for this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM