I went through a couple of posts on stackoverflow and also some blogs that describe what happens with ActivityTestRule and some basics about Instrumentation testing in android.But i am getting confused the more i read.
I have managed to write a test case but the issue I have is that I am not able to decide where to initialize MockWebServer and how to stop the webservice call (original) from happening. I read about Dagger but i do not know if i require it.
My activity class code of what i want to test is as under:
Call<List<Repository>> call = null;
call = new RestClient().getApiService().getRepositories();
And RestClient looks as under:
public class RestClient {
public static String BASE_URL = "https://api.github.com/";
private ApiService mApiService;
/**
* Initializes Retrofit and sets the base point of connection
*/
public RestClient() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
mApiService = retrofit.create(ApiService.class);
}
/**
* returns the instance of ApiService needed to make service calls
* @return
*/
public ApiService getApiService() {
return mApiService;
}
}
And ApiService as under:
public interface ApiService {
@GET("repositories")
Call<List<Repository>> getRepositories();
}
My InstrumentationTestClass looks as under:
@Rule
public ActivityTestRule<MainActivity> mActivityRule =
new ActivityTestRule<>(MainActivity.class, false, false);
@Before
public void setUp() throws Exception{
super.setUp();
mockWebServer = new MockWebServer();
mockWebServer.start();
injectInstrumentation(InstrumentationRegistry.getInstrumentation());
RestClient.BASE_URL = mockWebServer.url("/").toString();
}
@Test
@LargeTest
public void testDataLoaded() throws IOException {
String link = "<http://ift.tt/21LzYNZ;; rel=\"next\"," +
"<http://ift.tt/1REPThH;; rel=\"previous\"";
String fileName = "repositories.json";
MockResponse mockResponse = new MockResponse();
mockResponse.setHeader("Link", link);
mockWebServer.enqueue(mockResponse
.setResponseCode(200)
.setBody(RestClientTestHelper.getStringFromFile(getInstrumentation().getContext(), fileName)));
Intent intent = new Intent();
mActivityRule.launchActivity(intent);
assertNotNull(mockResponse.getBody());
}
Some questions and summary of what I have done:
- How do i prevent the actual network call from taking place and simply make use of mockWebServer to pick records from the json file in the assets folder?
- I tried initializing mockwebserver in the method beforeActivityLaunched but then tearDown returns with null pointer.
- I tried initializing mockwebserver in the testFragmentLoaded method and then launched the activity using intent but then it doesnot seem to prevent the web call
- Is what i am doing the right way? As i am new to automation testing :(
Please assist.
Aucun commentaire:
Enregistrer un commentaire