Karl Jamoralin Karl Jamoralin - 1 month ago 13
Android Question

Android junit: Method scheme in android.net.Uri&Builder Not Mocked

I'm trying to learn how to do unit tests in Android and I'm stuck with this particular issue. I searched for previous SO posts but none are relevant to this error. I'm getting this exception:


java.lang.RuntimeException: Method scheme in android.net.Uri$Builder not mocked. See http://g.co/androidstudio/not-mocked for details.


Why is it saying that method "scheme" of Uri.Builder needs to be mocked? Thanks!

MovieDBAPITest.java

package com.karljamoralin.popularmovies;

import org.junit.Test;
import static org.junit.Assert.assertEquals;

public class MovieDBAPITest {

MovieDBAPI movieDBAPI = new MovieDBAPI();

@Test
public void URLValidator() {
assertEquals("https://api.themoviedb.org/3/movie/top_rated?api_key=test&language=en-US",
movieDBAPI.buildUri("top_rated").toString());
}

@Test
public void test() {
assertEquals("a", movieDBAPI.test());
}

}


MovieDBAPI.java

package com.karljamoralin.popularmovies;

import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;

public class MovieDBAPI extends AsyncTask<String, Void, Void> {

final String TAG = getClass().getSimpleName();

@Override
protected Void doInBackground(String... params) {

Uri uri = buildUri(params[0]);

Log.v(TAG, uri.toString());

//Connect to URL

//Get string input

//Parse string input

//Return M

return null;
}

@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}

Uri buildUri(String mode) {

final String SCHEME = "https";
final String AUTHORITY = "api.themoviedb.org";
final String PATH1 = "3";
final String PATH2 = "movie";
final String API_KEY = "movie";
final String LANGUAGE = "language";

Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.scheme(SCHEME);
uriBuilder.authority(AUTHORITY);
uriBuilder.appendPath(PATH1);
uriBuilder.appendPath(PATH2);
uriBuilder.appendPath(mode);
uriBuilder.appendQueryParameter(API_KEY, "test");
uriBuilder.appendQueryParameter(LANGUAGE, "en-US");

return uriBuilder.build();

}

String test() {
return "a";
}

}

Answer

Yeah, that kind a test sucks with Android SDK. The Uri class is not implemented in the dev jar.

My advise would be to make wrapper classes for those situations and use those wrappers in your tests. Other possibilities are to use Robolectric or Android Instrumentation Tests.