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

0 android android-volley

我的Android应用程序通过REST API与后端服务进行通信.我想嘲笑这个API来快速开发前端.我使用android volley作为客户端网络库.

Jan*_*ken 8

您可以使用依赖注入设计模式.

基本上,您指定了一个接口,该接口定义了与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);
}
Run Code Online (Sandbox Code Playgroud)

现在,在需要查询后端的类中,指定一个注入器.这可以通过多种方式完成(例如构造函数注入,setter注入 - 有关更多详细信息,请参阅wiki文章).使用注入器可以将依赖项的实现注入依赖于它的类中.我们假设您使用构造函数注入.使用后端的类看起来像这样:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您创建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;
    }
}
Run Code Online (Sandbox Code Playgroud)

并使用它来实例化您的依赖类:

DepedentClass restClient = new DepedentClass(new MockRestService());
Run Code Online (Sandbox Code Playgroud)

现在您可以使用restClient它连接到您的实际后端.它将简单地返回可用于开发前端的虚拟对象.

当您完成前端并准备好实现后端时,您可以通过创建另一个实现来实现这一点,该实现DataSupplier建立与REST后端的连接并查询它以获取真实对象.我们假设您将此实施命名为RestService.现在,你可以简单地替换构造创建MockRestService与你的RestService构造函数如下所示:

DepedentClass restClient = new DepedentClass(new RestService());
Run Code Online (Sandbox Code Playgroud)

而且你拥有它:通过交换单个构造函数,您可以将前端代码从使用虚拟对象更改为使用真正的REST交付对象.你甚至可以有一个调试标志,并restClient根据你的应用程序的状态(调试或发布)创建:

boolean debug = true;
DependentClass restClient = null;
if (debug) {
    restClient = new DepedentClass(new MockRestService());
} else {
    restClient = new DepedentClass(new RestService());
}
Run Code Online (Sandbox Code Playgroud)