我有一个仪器测试,效果很好:
@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());
}
但是我不知道如何在后台使用mockito和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测试文件夹运行时代码会失败,而从instrumentation测试文件夹运行时代码会工作
Reader in=postRequest。sendRequest();//正在这里引发空指针异常
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;
}
}
顺致敬意,
奥勒良