samedi 2 juillet 2016

MockWebserver and Retrofit 2.0

Trying to unit test a Retrofit 2.0 response using MockWebServer. I have the webserver setup, but the problem occurs when i am trying to pass a mock json file as a response. To illustrate, my folder structure is:

src->test->java->package_name->class_name.java

src->test->resources->list_success.json

My unit test:

@Before
    public void setUp() throws IOException {
        MockitoAnnotations.initMocks(this);
        commonFragmentPresenter = new CommonFragmentPresenter(mainFragmentPresenterInterface);
        mockWebServer = new MockWebServer();
        mockWebServer.start();
        RestClient.URL = mockWebServer.url("/").toString();    

    }

  @Test
    public void testThatEventBusIsReceivedOnMakingServiceCall() throws Exception {
        System.out.println(CommonFragmentPresenterTest.class.getResource(".").getPath());
        mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(getStringFromFile("list_success.json")));
        commonFragmentPresenter.getData("Store","1");
        verify(mainFragmentPresenterInterface).setDataForRecyclerViewAdapter(anyList());
    }

  private  String getStringFromFile(String filePath) throws Exception {

        final InputStream stream =getClass().getClassLoader().getResourceAsStream(filePath);
        String ret = convertStreamToString(stream);
        stream.close();
        return ret;
    }

public  String convertStreamToString(InputStream is) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        sb.append(line).append("\n");
    }
    reader.close();
    return sb.toString();
}

I keep getting a null pointer while trying to use the getResourceAsStream. Am i missing something here?

Aucun commentaire:

Enregistrer un commentaire