java - 在 Android 中使用 Espresso 的正确方法是什么?

标签 java android unit-testing android-espresso

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

最佳答案

尝试使用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);


    }

关于java - 在 Android 中使用 Espresso 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43485077/

相关文章:

java - OneToMany Hibernate 保存级联问题

Java不能做声明?

java - 错误: cannot find symbol (using replaceAll ) codenameone

ruby-on-rails - 如何防止加载 RSpec 助手

PHP 单元测试错误 - PHPUnit_Util_DeprecatedFeature_Logger

java.lang.ClassNotFoundException : com. mysql.jdbc.Driver - 不工作

android - 使用谷歌地图 v2 发布 key 发布应用程序,如何制作 apk 文件?

android - 关闭对话框导致 Activity 完成

visual-studio-2008 - VS 2008 的代码覆盖工具

java - 使用其他包中的私有(private)构造函数扩展类