无需工具测试,即可在junit和mockito中进行Android测试Web服务

时间:2018-09-28 08:46:05

标签: android junit mockito android-instrumentation

我有这个可以正常运行的仪器测试:

@Test
    public void testWebService() {
        // Context of the app under test.
        Context appContext = InstrumentationRegistry.getTargetContext();

        AuthService authService = new AuthService();
        try {
            AuthenticateResult authenticateResult = authService.authenticate("xx@xxx.com", "xxxx", "xxxxxxx");
            assertNotNull(authenticateResult.getAuthenticationToken());
            assertNotEquals(authenticateResult.getAuthenticationToken(),"");
        } catch (Exception e) {
            fail(e.getMessage());
        }

        assertEquals("com.roscasend.android.testa", appContext.getPackageName());
    }

但是我不知道如何在不进行仪器测试的情况下,在后台使用带有junit的嘲笑来测试相同的Web服务:

@Test
    public void testWeb(){
        AuthService mockCalculator = Mockito.spy(AuthService.class);
        EncryptionProvider encryptionProvider = Mockito.spy(EncryptionProvider.class);
        try {
            Mockito.when(mockCalculator.authenticate("xx@xxx.com", "xxxx", "xxxxxxx",
                    encryptionProvider)).thenReturn(authenticateResult);

        } catch (Exception e) {
            fail(e.getMessage());
        }
    }

// this is the authenticate method from AuthServer class which is called above 

    public AuthenticateResult authenticate(String mUser, String mPassword, String imei,
                                               EncryptionProvider encryptionProvider) throws Exception {
            String url = "http://xxx.xxx.xx.xxx/xxxserver/" + "restXXX" + AUTHENTICATE;
            //Log.d(TAG, "Authenticating user: " + url);
    //      headers.put("Content-Type", "application/json");

            final JSONObject jsonBody = new JSONObject();

            jsonBody.put("userName", mUser);

            String key = encryptionProvider.buildValidKey(imei);
            if (!mPassword.isEmpty()) {
                mPassword = encryptionProvider.encrypt(mPassword, key);
            }

            jsonBody.put("password", mPassword);
            jsonBody.put("deviceUniqueID", key);


            IHttpRequest postRequest = new PostRequest(url, jsonBody);
            try {
                Reader in = postRequest.sendRequest(); // is throwing an null pointer exception here

                Gson gson = new Gson();

                if (in != null) {
                    AuthenticateRestBean authenticateRestBean = gson.fromJson(in, AuthenticateRestBean.class);
                    if (authenticateRestBean != null) {
                        return authenticateRestBean.getAuthenticateResult();
                    }
                }
            } catch (Exception e) {
                InputStream inputStream = postRequest.getErrorStream();
                if (inputStream != null) {
                    String errorStream = AppUtil.convertInputStreamToString(inputStream);
                    throw new Exception(errorStream);
                } else {
                    throw e;
                }

            }

            return null;
        }

我无法弄清楚为什么从后台junit测试文件夹运行时代码在这里失败,而从仪器测试文件夹运行时却能正常工作

Reader in = postRequest.sendRequest(); //在此处引发空指针异常

enter image description here

import android.support.v4.util.SimpleArrayMap;

import org.json.JSONObject;

import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Locale;

import ro.star.logger.Logger;
import ro.star.sca.business.util.AppConstants;

public class PostRequest implements IHttpRequest {

private static final String TAG = PostRequest.class.getName();

private final String url;
private final JSONObject jsonObject;
private SimpleArrayMap<String, String> headers;

public static final String AUTH_TOKEN_HEADER = "AuthTokenHeader";
public static final String AUTH_GUID_HEADER = "MachineGuidHeader";

private InputStream errorStream;

public PostRequest(String url, JSONObject jsonObject) {
    this.url = url;
    this.jsonObject = jsonObject;

    headers = new SimpleArrayMap<>();
    headers.put("Content-Type", "application/json");
    headers.put("Accept-Language", Locale.getDefault().getLanguage());
    headers.put(PostRequest.AUTH_TOKEN_HEADER, AppConstants.TOKEN);
    headers.put(PostRequest.AUTH_GUID_HEADER, AppConstants.GUID);
}

public Reader sendRequest() throws Exception {

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("POST");
    con.setConnectTimeout(AppConstants.TIMEOUT);
    con.setReadTimeout(AppConstants.TIMEOUT);

    if (headers != null && !headers.isEmpty()) {
        for (int i=0; i< headers.size(); i++) {
            String key = headers.keyAt(i);
            String value = headers.get(key);
            con.setRequestProperty(key, value);
        }
    }

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(jsonObject.toString());
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    Logger.i(TAG, "\nSending 'POST' request to URL : " + url);
    Logger.i(TAG, "Post parameters : " + jsonObject.toString());
    Logger.i(TAG, "Response Code : " + responseCode);

    errorStream = con.getErrorStream();
    return new InputStreamReader(con.getInputStream(), "UTF-8");
}

@Deprecated
public InputStream sendRequestIS() throws Exception {

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("POST");
    con.setConnectTimeout(AppConstants.TIMEOUT);
    con.setReadTimeout(AppConstants.TIMEOUT);

    if (headers != null && !headers.isEmpty()) {
        for (int i=0; i< headers.size(); i++) {
            String key = headers.keyAt(i);
            String value = headers.get(key);
            con.setRequestProperty(key, value);
        }
    }

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(jsonObject.toString());
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    Logger.i(TAG, "\nSending 'POST' request to URL : " + url);
    Logger.i(TAG, "Post parameters : " + jsonObject.toString());
    Logger.i(TAG, "Response Code : " + responseCode);

    return con.getInputStream();
}

public InputStream getErrorStream() {
    return errorStream;
}

}

最好的问候, 奥雷利亚

0 个答案:

没有答案