简体   繁体   English

我如何在 Android 应用程序中模拟 REST 后端

[英]How do i mock REST backend in an android app

My android app communicate with backend service through REST API .我的 android 应用程序通过 REST API 与后端服务通信。 I want to mock out this API to quickly develop the front end.我想模拟这个 API 来快速开发前端。 I am using android volley as client side networking library.我使用 android volley 作为客户端网络库。

You can use the dependency injection design pattern for this.您可以为此使用依赖项注入设计模式。

Basically you specify an interface that defines a set of methods corresponding to the queries you have in your REST backend, eg:基本上,您指定一个接口,该接口定义一组与您在 REST 后端的查询相对应的方法,例如:

interface DataSupplier {
    // Lookup user by ID
    User getUser(int id);

    // Get all blog posts posted by a specific user.
    List<BlogPost> getUsersBlogPosts(int userId);
}

Now in the class where you need to query the backend, you specify an injector.现在在需要查询后端的类中,指定一个注入器。 This can be done in multiple ways (eg constructor injection, setter injection - see the wiki article for more details).这可以通过多种方式完成(例如构造函数注入、setter 注入——更多详细信息,请参阅 wiki 文章)。 An injector lets you inject an implementation of the dependency into the class that depends on it.注入器允许您将依赖项的实现注入到依赖它的类中。 Let us assume you use constructor injection.让我们假设您使用构造函数注入。 Your class that uses the backend would look like this:您使用后端的类将如下所示:

public class DependentClass {

    private final DataSupplier mSupplier;

    public DependentClass(DataSupplier dataSupplier) {
        mSupplier = dataSupplier;
    }

    // Now you simply call mSupplier whenever you need to query the mock
    // (or - later in development - the real) REST service, e.g.:
    public void printUserName() {
        System.out.println("User name: " + mSupplier.getUser(42).getName());
    }
}

Then you create a mock implementation of DataSupplier :然后创建DataSupplier的模拟实现:

public class MockRestService implements DataSupplier {

    @Override
    public User getUser(int id) {
        // Return a dummy user that matches the given ID
        // with 'Alice' as the username.
        return new User(id, "Alice");
    }

    @Override
    public List<BlogPost> getUsersBlogPosts(int userId) {
        List<BlogPost> result = new ArrayList<BlogPost>();
        result.add(new BlogPost("Some Title", "Some body text"));
        result.add(new BlogPost("Another Title", "Another body text"));
        result.add(new BlogPost("A Third Title", "A third body text"));
        return result;
    }
}

and use that to instantiate your dependent class:并使用它来实例化您的依赖类:

DepedentClass restClient = new DepedentClass(new MockRestService());

Now you can use restClient as if it was connected to your actual backend.现在您可以使用restClient ,就好像它已连接到您的实际后端一样。 It will simply return dummy objects that you can use to develop your front end.它只会返回可用于开发前端的虚拟对象。

When you are done with your front end and ready to implement your backend, you do so by creating another implementation of DataSupplier that sets up a connection to your REST backend and queries it for real objects.当您完成前端并准备好实现后端时,您可以通过创建另一个DataSupplier实现来实现,该实现设置到 REST 后端的连接并查询真实对象。 Let us say you name this implementation RestService .假设您将此实现命名为RestService Now you can simply replace the constructor creating the MockRestService with your RestService constructor like so:现在你可以简单地用你的RestService构造函数替换创建MockRestService的构造函数,如下所示:

DepedentClass restClient = new DepedentClass(new RestService());

And there you have it: by swapping a single constructor call, you can change your front end code from using dummy objects to using real REST-delivered objects.就这样:通过交换单个构造函数调用,您可以将前端代码从使用虚拟对象更改为使用真正的 REST 交付对象。 You could even have a debug flag and create the restClient according to the state of your application (debug or release):您甚至可以有一个调试标志并根据您的应用程序的状态(调试或发布)创建restClient

boolean debug = true;
DependentClass restClient = null;
if (debug) {
    restClient = new DepedentClass(new MockRestService());
} else {
    restClient = new DepedentClass(new RestService());
}

I've recently created RESTMock .我最近创建了RESTMock It is a library for Mocking REST API's in android tests.它是一个用于在 android 测试中模拟 REST API 的库。 It can be used during development though.但它可以在开发过程中使用。 You would need to set it up following the README on github and create a basic Android Instrumentation test that would start your app and do nothing.您需要按照 github 上的 README 进行设置,并创建一个基本的 Android Instrumentation 测试,该测试将启动您的应用程序并且什么也不做。 This way the app is started with the Mock Server in background.通过这种方式,应用程序在后台以 Mock Server 启动。

Example test:示例测试:

public class SmokeTest {
    @Rule public ActivityTestRule<MainActivity> rule = new ActivityTestRule<MainActivity>(
            SplashActivity.class,
            true,
            false);


    @Test
    public void smokeTest() throws InterruptedException {
        rule.launchActivity(null);
        Thread.sleep(10000000);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将我的 Android 应用程序连接到后端? - How do I connect my Android app to backend? 如何从Android应用向App Engine后端发出请求? - How do I make requests from an Android app to an App Engine backend? 将在网络服务中读取的Android应用程序我是否使用Soap或Rest,以及如何在其中读取 - Android app that will read in a webservice Do I use Soap or Rest and How do I read it in 如何在没有后端服务器的 Android 应用程序中为 PhotosLibraryClient 验证用户 - How do you authenticate a user for PhotosLibraryClient in an Android app with no backend server 我如何使用 REST/HTTP 将 android 应用程序与 web 应用程序链接起来 - How do i link android app with web app using REST/HTTP 我有一个现有的 Django Webapp,如何制作 rest API 以将 webapp 与 ZC31B323617ECCECA84 集成 - I have an existing Django Webapp, how do I make a rest API to integrate the webapp with an android app? 我如何将Android应用程序连接到Django后端 - How can I connect android app to django backend 如何在Android测试中创建模拟服务? - How do I create a mock service in an Android test? 如何验证来自Android App的SharePoint REST调用? - How can I authenticate SharePoint REST calls from Android App? 如何在 Spring 后端使用 Android 执行 GET - How to do a GET with Android on a Spring Backend
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM