2017-04-19 8 views
0

내 안드로이드 애플 리케이션을위한 에스프레소 테스트를 실행하려고하지만, 저를 괴롭히는 문제가 있습니다. MainActivity에서 일부보기의 가시성은 net에서로드 된 데이터에 따라 다르지만 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