SAPUI5 (23) - 使用mock server模拟oData提供者

模拟服务器(mock server)的作用

所有的应用程序都涉及CRUD操作,openui5在真实的场景中是通过oData和后端SAP系统交互。但在开发过程中,为了测试的需要,可以使用模拟服务器,openui5将模拟服务器称作mock server。模拟服务器的基本功能是模拟oData数据提供者,截获应用程序的对服务器端的htpp或https请求,并传回模拟请求的回应。从openui5开发的这一侧来看,可以降低与真实后端的耦合。

mock server简单介绍

openui5有自己的mocke server模块,但我这里参照《SAPUI5 Comprehensive Guide》一书,使用另外一个框架:github上的fakerest,基于sinon(地址:点击)。支持CRUD操作,基本使用方法如下:

    1. FakeRest.min.js文件在webapp的service文件夹下。并添加对js文件的引用。
<script src="../service/FakeRest.min.js"></script>
    1. mockServerTest.html文件放在webapp下的test文件夹下。用于测试代码。
    1. 加载sinon模块
jQuery.sap.require("sap.ui.thirdparty.sinon");
    1. 加载数据并初始化fake server和sinon server
var data = {
    'authors': [
        { id: 0, first_name: 'Leo', last_name: 'Tolstoi' },
        { id: 1, first_name: 'Jane', last_name: 'Austen' }
    ],
    'books': [
        { id: 0, author_id: 0, title: 'Anna Karenina' },
        { id: 1, author_id: 0, title: 'War and Peace' },
        { id: 2, author_id: 1, title: 'Pride and Prejudice' },
        { id: 3, author_id: 1, title: 'Sense and Sensibility' }
    ],
    'settings': {
        language: 'english',
        preferred_format: 'hardback',
    }
};
    
// initialize fake REST server
var restServer = new FakeRest.Server();
restServer.init(data);

// use sinon.js to monkey-patch XmlHttpRequest
var server = sinon.fakeServer.create();
server.respondWith(restServer.getHandler());
    1. 在mock server中实现增删改查操作
// 使用GET请求查询所有的author
var req = new XMLHttpRequest();
req.open("GET", "/authors", false);
req.send(null);
console.log(req.responseText);

// 使用GET请求查询第四条book:/books/3
req = new XMLHttpRequest();
req.open("GET", "/books/3", false);
req.send(null);
console.log(req.responseText);

// 使用POST请求插入数据
req = new XMLHttpRequest();
req.open("POST", "/books", false);
var updateData = JSON.stringify({
    id: 4, author_id:1, title:'Emma'});
req.send(updateData);
console.log(req.responseText);

// 使用PUT请求更改数据
req = new XMLHttpRequest();
req.open("PUT", "/books/2", false);
var modifyData = JSON.stringify({
    title:'傲慢与偏见'});
req.send(modifyData);
console.log("修改:");
console.log(req.responseText);

// 使用GET请求查询所有的books
req = new XMLHttpRequest();
req.open("GET", "/books", false);
req.send(null);
console.log("修改后:");
console.log(req.responseText);

// Delete数据
req = new XMLHttpRequest();
req.open("DELETE", "/books/4", false);
req.send(null);
console.log("删除:");
console.log(req.responseText);

// 使用GET请求查询所有的books
req = new XMLHttpRequest();
req.open("GET", "/books", false);
req.send(null);
console.log("删除后:");
console.log(req.responseText);

创建含有mock server的代码框架

index.html

随着我们编写的功能增多,项目文件包含的文件也越来越复杂。为了方便后面的学习,我打算创建一个起始的代码框架。文件结构如下:

Project Files
Project Files

起始代码应该能够运行,并且在今后增加功能时,尽量少变更。我们先来看index.html:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv='Content-Type' content='text/html;charset=UTF-8' />

<script src="service/FakeRest.min.js"></script>

<script src="../resources/sap-ui-core.js" id="sap-ui-bootstrap"
    data-sap-ui-libs="sap.m" data-sap-ui-preload="async"
    data-sap-ui-theme="sap_bluecrystal"
    data-sap-ui-xx-bindingSyntax="complex"
    data-sap-ui-resourceroots='{"stonewang.sapui5.demo": "./"}'>
    
</script>

<script>
    sap.ui.getCore().attachInit(function() {
        sap.ui.require([ 
                "sap/m/Shell",
                "sap/ui/core/ComponentContainer",
                "stonewang/sapui5/demo/Component",
                "sap/ui/thirdparty/sinon" 
        ], 
                
        function(Shell, ComponentContainer, Component) {

            jQuery.ajax({
                url : "service/suppliers.json",
                success : function(oData) {
                    initAppWithFakeRest(oData);
                },
                error : function() {
                    alert("Could not start server");
                }
            });

            var initAppWithFakeRest = function(oData) {
                // initialize fake REST server
                var restServer = new FakeRest.Server();
                restServer.init(oData);

                var server = sinon.fakeServer.create();
                server.xhr.useFilters = true;
                server.autoRespond = true;
                server.autoRespondAfter = 0;

                server.xhr.addFilter(function(method, url) {
                    //whenever the this returns true the request will not faked
                    return !url.match(/Suppliers/);
                });

                // use sinon.js to monkey-patch XmlHttpRequest
                server.respondWith(restServer.getHandler());

                // initialize the UI component
                new Shell({
                    app : new ComponentContainer({
                        height : "100%",
                        component : new Component({
                            id : "mvcAppComponent"
                        })
                    })
                }).placeAt("content");
            }
        });
    });
</script>

</head>
<body class="sapUiBody" role="application">
    <div id="content"></div>
</body>
</html>

代码说明:

  • jQuery.ajax通过url参数加载文本文件,如果加载成功,执行initAppWithFakeRest,如果失败,提示不能启动服务器。
jQuery.ajax({
    url : "service/suppliers.json",
    success : function(oData) {
        initAppWithFakeRest(oData);
    },
    error : function() {
        alert("Could not start server");
    }
});
  • initAppWithFakeRest函数中,初始化fake server、sinon server、component conatiner和component:
var initAppWithFakeRest = function(oData) {
    // initialize fake REST server
    var restServer = new FakeRest.Server();
    restServer.init(oData);

    var server = sinon.fakeServer.create();
    server.xhr.useFilters = true;
    server.autoRespond = true;
    server.autoRespondAfter = 0;

    server.xhr.addFilter(function(method, url) {
        //whenever the this returns true the request will not faked
        return !url.match(/Suppliers/);
    });

    // use sinon.js to monkey-patch XmlHttpRequest
    server.respondWith(restServer.getHandler());

    // initialize the UI component
    new Shell({
        app : new ComponentContainer({
            height : "100%",
            component : new Component({
                id : "mvcAppComponent"
            })
        })
    }).placeAt("content");
}

Component.js

Component.js中,通过jQuery.ajax方法发起GET请求,请求成功则设置application model为oData。

sap.ui.define([
          "sap/ui/core/UIComponent",
          "sap/ui/model/resource/ResourceModel",
          "sap/ui/model/json/JSONModel",
          "stonewang/sapui5/demo/model/AppModel"
    ], 
      
    function (UIComponent, ResourceModel, JSONModel, AppModel) {
        "use strict";

        return UIComponent.extend("stonewang.sapui5.demo.Component", {
        
            metadata : {
                manifest: "json"
            },

            init : function () {
                // call the base component's init function
                UIComponent.prototype.init.apply(this, arguments);              
                
                 var oAppModel = new JSONModel("/Suppliers");           

                 // set application data
                jQuery.ajax({
                    type : "GET",
                    contentType : "application/json",
                    url : "/Suppliers",
                    dataType : "json",
                    success : function(oData) {
                        oAppModel.setData(oData);
                    },
                    error : function() {
                        jQuery.sap.log.debug(
                            "Something went wrong while retrieving the data");
                    }
                });             
                
                this.setModel(oAppModel);
                
                // create the views based on the url/hash
                this.getRouter().initialize();
            } // end of init function
        });
});

设置启动时候进入notFound视图

manifest.json中,设置pattern为空的时候,target为notFound,从而进入not found视图,后面再修改:

"routes": [
    {
        "pattern": "",
        "name": "notFound",
        "target": "notFound"
    }

notFound视图

<core:View xmlns:core="sap.ui.core" 
           xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m"
        xmlns:html="http://www.w3.org/1999/xhtml">
        
    <MessagePage
            title="{i18n>notFoundTitle}"
            text="{i18n>notFoundText}"
            icon="{sap-icon://document}"
            id="page">
    </MessagePage>

</core:View>

搭建本篇的框架代码,作为后面使用模拟服务器进行增删改查的基础。

Source Code

23_zui5_mock_server_skeleton

参考

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容