Step 27: Mock Server Configuration

opensapkr·2019년 7월 5일
0

ui5-Walkthrough

목록 보기
28/39

App을 개발을 테스트하기 위해 모의 서버 (mock server) SAPUI5 기능으로 시뮬레이션 할 수 있다.
로컬 파일을 제공하지만 사실적으로 bank-end 시스템을 시뮬레이션 한다.
또한 model 인스턴스화 부분을 변경하여 model이 descriptor에서 구성되고 SAPUI5에의해 자동으로 instance된다.
이렇게하면 code에서 model instance를 처리 할 필요가 없다.

Preview

Coding

Walkthrough - Step 27.

Folder Structure

webapp/test/mockServer.html

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>SAPUI5 Walkthrough - Test Page</title>
	<script
		id="sap-ui-bootstrap"
		src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js"
		data-sap-ui-theme="sap_belize"
		data-sap-ui-resourceroots='{
			"sap.ui.demo.walkthrough": "../"
		}'
		data-sap-ui-oninit="module:sap/ui/demo/walkthrough/test/initMockServer"
		data-sap-ui-compatVersion="edge"
		data-sap-ui-async="true">
	</script>
</head>
<body class="sapUiBody" id="content">
	<div data-sap-ui-component data-name="sap.ui.demo.walkthrough" data-id="container" data-settings='{"id" : "walkthrough"}'></div>
</body>
</html>

App Project의 구조를 테스트와 실제 구동 폴더로 구분 할 것이다.
test 폴더에는 실제 서비스를 호출하지 않고 테스트 모드에서 우리의 응용 프로그램을 시작할 새로운 HTML 페이지 mockServer.html이 포함되어 있다.

신규 localService folder에는 OData에 대한 metadata.xml 서비스 설명 파일 Local Data가 Real service처럼 simulate를 수행할 mockserver.js 파일이 있다.
폴더 mockdata에는 Local test data인 Invoices.json이 들어 있다.

note: 만약 real 서비스에 연결할 수 없거나 이전 단계의 proxy 구성이 작동하지 않으면 mockServer.html 파일을 항상 사용할 수 있다.
그러면 시뮬레이트 된 test 데이터가있는 App이 표시된다.
index.html 파일은 항상 원격 서버에서 데이터를 로드 한다.

webapp/test/initMockServer.js (New)

sap.ui.define([
	"../localService/mockserver"
], function (mockserver) {
	"use strict";

	// initialize the mock server
	mockserver.init();

	// initialize the embedded component on the HTML page
	sap.ui.require(["sap/ui/core/ComponentSupport"]);
});

mockServer.html이 호출될때 dat-ui-oinit에 설정한 경로로 initMockServer.js가 호출이 된다.
이 스크립트는 localService 폴더에 있는 mockserver를 종속성으로 받는다.

해당 종속 파일은 로컬 테스트 서버로 initMockServer를 로드하기 전에 mockser부터 호출을 한다.
이렇게 하면 mockServer.html 파일로 응용 프로그램을 시작할 때 테스트 서버에서 로컬로 처리하는 모든 요청을 알 수 있다.

webapp/localService/mockdata/Invoices.json (New)

[
  {
	"ProductName": "Pineapple",
	"Quantity": 21,
	"ExtendedPrice": 87.2000,
	"ShipperName": "Fun Inc.",
	"ShippedDate": "2015-04-01T00:00:00",
	"Status": "A"
  },
  {
	"ProductName": "Milk",
	"Quantity": 4,
	"ExtendedPrice": 9.99999,
	"ShipperName": "ACME",
	"ShippedDate": "2015-02-18T00:00:00",
	"Status": "B"
  },
  {
	"ProductName": "Canned Beans",
	"Quantity": 3,
	"ExtendedPrice": 6.85000,
	"ShipperName": "ACME",
	"ShippedDate": "2015-03-02T00:00:00",
	"Status": "B"
  },
  {
	"ProductName": "Salad",
	"Quantity": 2,
	"ExtendedPrice": 8.8000,
	"ShipperName": "ACME",
	"ShippedDate": "2015-04-12T00:00:00",
	"Status": "C"
  },
  {
	"ProductName": "Bread",
	"Quantity": 1,
	"ExtendedPrice": 2.71212,
	"ShipperName": "Fun Inc.",
	"ShippedDate": "2015-01-27T00:00:00",
	"Status": "A"
  }
]

이전에 생성한 Invocies.json 파일을 webapp/localService/mockdata 경로로 옮겨준다.
해당 파일은 자동으로 서버에서 읽는다.
이전에 webapp/Invocies.json은 이제 삭제해도 된다.

webapp/localService/metadata.xml (New)

<edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx">
	<edmx:DataServices m:DataServiceVersion="1.0" m:MaxDataServiceVersion="3.0"
					   xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
		<Schema Namespace="NorthwindModel" xmlns="http://schemas.microsoft.com/ado/2008/09/edm">
			<EntityType Name="Invoice">
				<Key>
					<PropertyRef Name="ProductName"/>
					<PropertyRef Name="Quantity"/>
					<PropertyRef Name="ShipperName"/>
				</Key>
				<Property Name="ShipperName" Type="Edm.String" Nullable="false" MaxLength="40" FixedLength="false"
						  Unicode="true"/>
				<Property Name="ProductName" Type="Edm.String" Nullable="false" MaxLength="40" FixedLength="false"
						  Unicode="true"/>
				<Property Name="Quantity" Type="Edm.Int16" Nullable="false"/>
				<Property Name="ExtendedPrice" Type="Edm.Decimal" Precision="19" Scale="4"/>
			</EntityType>
		</Schema>
		<Schema Namespace="ODataWebV2.Northwind.Model" xmlns="http://schemas.microsoft.com/ado/2008/09/edm">
			<EntityContainer Name="NorthwindEntities" m:IsDefaultEntityContainer="true" p6:LazyLoadingEnabled="true"
							 xmlns:p6="http://schemas.microsoft.com/ado/2009/02/edm/annotation">
				<EntitySet Name="Invoices" EntityType="NorthwindModel.Invoice"/>
			</EntityContainer>
		</Schema>
	</edmx:DataServices>
</edmx:Edmx>

메타 데이터 파일에는 서비스 인터페이스에 대한 정보가 있어 자동으로 로드 된다.
서비스 URL을 호출하고 마지막에 $ metadata (예 : http://services.odata.org/V2/Northwind/Northwind.svc/$metadata)를 추가하여 데이터를 불러올 수 있다.

모의 서버는 실제 OData 서비스를 시뮬레이트 하기 위해 해당 파일을 읽고 결과를 반환하여 XML 또는 JSON 형식으로 앱에서 사용할 수 있다.

webapp/localService/mockserver.js (New)

sap.ui.define([
	"sap/ui/core/util/MockServer",
	"sap/base/util/UriParameters"
], function (MockServer, UriParameters) {
	"use strict";

	return {
		init: function () {
			// create
			var oMockServer = new MockServer({
				rootUri: "https://services.odata.org/V2/Northwind/Northwind.svc/"
			});

			var oUriParameters = new UriParameters(window.location.href);

			// configure mock server with a delay
			MockServer.config({
				autoRespond: true,
				autoRespondAfter: oUriParameters.get("serverDelay") || 500
			});

			// simulate
			var sPath = "../localService";
			oMockServer.simulate(sPath + "/metadata.xml", sPath + "/mockdata");

			// start
			oMockServer.start();
		}
	};

});

metadata.xml 파일을 통해 Northwind 서버 OData 요청을 시뮬레이팅하는 모의 서버를 초기화하는 코드를 작성할 수 있다.
표준 OpenUI5 MockServer 모듈을 종속성 로드 후 서버를 시작하는 init 메소드에 helper Object (도우미 객체)를 만든다.

이 메서드는 위의 mockServer.html 파일에서 구성 요소 초기화 전에 호출된다.
init 메소드는 실제 서비스 호출과 동일한 URL을 가진 MockServer 인스턴스를 생성한다.

구성 매개 변수 rootUri의 URL은 manifest.json파일의 데이터 소스에 대해 정의된 URI와 일치해야 한다.
실제 서비스 대신 테스트 서버에서 URL을 제공한다.

다음으로 서버가 자동으로 응답하고 일반적인 서버 응답 시간을 위해 1 초의 지연을 한다.
그렇지 않으면 호출을 시뮬레이트하기 위해 수동으로 respond 메소드를 호출해야한다.

서비스를 시뮬레이트하기 위해 metadata.xml에 대한 경로를 사용하여 MockServer 인스턴스에서 simulate 메소드를 호출 한다.
그러면 로컬 파일 시스템에서 테스트 데이터를 읽고 실제 서비스에 대한 URL 패턴을 설정한다.
이는 네트워크 연결이 없이 로컬 테스트가 가능하다.

webapp/package.json (New)

{
  "name": "WalkthroughTutorial",
  "private": true,
  "version": "1.0.0",
  "author": "SAP SE",
  "description": "UI5 Demo App - Walkthrough Tutorial",
  "scripts": {
    "serve": "ui5 serve --open /index.html",
    "mock": "ui5 serve --open /test/mockServer.html",
    "proxy": "node proxy.js"
  },
  "devDependencies": {
    "cors-anywhere": "^0.4.1"
  }
}

scripts에 mock 명령어를 추가하고 npm run mock 명령어를 통해 테스트 해보자

Conventions

  • webapp/test. 폴더는 비생상적인 코드만 포함된다.

  • mock 데이터와 mockServer 시작 스크립트는 webapp/localService 폴더에 저장된다.

  • mockServer를 시작하는 스크립트는 mockserve.js 이다.

Mock Server

API Reference: sap.ui.core.util.MockServer

Create a Northwind Destination

profile
UI5/Fiori/BTP 도큐먼트 번역 및 관련 정보 공유합니다.

0개의 댓글