2017-04-19 58 views
0

我正在尝试为我的android应用程序运行Espresso测试,但存在一直困扰着我的问题。在MainActivity中,某些视图的可见性取决于从网络加载的数据,但在MainActivityTest中,我无法操作加载数据的过程,因此我不知道真实数据,哪个视图应该显示以及哪个视图不应显示。结果,我不知道如何继续我的测试。任何人都可以告诉我如何处理这种情况?谢谢!在Android中使用Espresso的正确方法是什么?

回答

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

相关问题