【问题标题】:What is the right way to use Espresso in android?在 android 中使用 Espresso 的正确方法是什么?
【发布时间】:2017-04-19 02:06:02
【问题描述】:

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

【问题讨论】:

    标签: java android unit-testing 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("/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("/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);
    
    
        }
    

    【讨论】:

    • 谢谢,我试试看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 2018-12-20
    • 2021-08-14
    • 2021-05-31
    • 2018-04-28
    相关资源
    最近更新 更多