2017-04-19 1 views
0

私はアンドロイドアプリのエスプレッソテストを実行しようとしていますが、問題を抱えています。 MainActivityでは、一部のビューの可視性はネットからロードされたデータに依存しますが、MainActivityTestではデータのロード処理を操作できないため、実際のデータと表示するビューと表示しないビューはわかりません。その結果、テストを続ける方法がわかりません。誰でもこの状況をどのように処理するか教えていただけますか?ありがとう!アンドロイドでエスプレッソを使用する正しい方法は何ですか?

答えて

1

MockWebServerライブラリをお試しください。テストでhttpレスポンスを模擬することができます。

 /** 
    * Constructor for the test. Set up the mock web server here, so that the base 
    * URL for the application can be changed before the application loads 
    */ 
    public MyActivityTest() { 
     MockWebServer server = new MockWebServer(); 
     try { 
      server.start(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     //Set the base URL for the application 
     MyApplication.sBaseUrl = server.url("/").toString(); 


     //Create a dispatcher to handle requests to the mock web server 
     Dispatcher dispatcher = new Dispatcher() { 

      @Override 
      public MockResponse dispatch(RecordedRequest recordedRequest) throws InterruptedException { 
      try { 
       //When the activity requests the profile data, send it this 
       if(recordedRequest.getPath().startsWith("https://stackoverflow.com/users/self")) { 
        String fileName = "profile_200.json"; 
        InputStream in = this.getClass().getClassLoader().getResourceAsStream(fileName); 
        String jsonString = new String(ByteStreams.toByteArray(in)); 
        return new MockResponse().setResponseCode(200).setBody(jsonString); 
       } 
       //When the activity requests the image data, send it this 
       if(recordedRequest.getPath().startsWith("https://stackoverflow.com/users/self/media/recent")) { 
        String fileName = "media_collection_model_test.json"; 
        InputStream in = this.getClass().getClassLoader().getResourceAsStream(fileName); 
        String jsonString = new String(ByteStreams.toByteArray(in)); 
        return new MockResponse().setResponseCode(200).setBody(jsonString); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 

      return new MockResponse().setResponseCode(404); 
      } 
     }; 
     server.setDispatcher(dispatcher); 


    } 
+0

ありがとう、私はそれを試してみます。 – vesper

関連する問題