mountebank_如何使用Mountebank和Node.js模拟服务

本文详细介绍了如何使用Node.js和开源工具Mountebank创建服务模拟,帮助开发者在复杂服务环境中测试代码,避免依赖未完成或不可控的服务。通过创建模拟服务,你可以设置默认响应和特定测试数据,提高开发和测试效率。教程覆盖了从创建Node.js应用到建立数据支持的模拟服务的完整步骤,适合需要服务虚拟化的开发者参考。
摘要由CSDN通过智能技术生成

mountebank

The author selected the Open Internet/Free Speech Fund to receive a donation as part of the Write for DOnations program.

作者选择了“ 开放互联网/言论自由基金会”作为“ Write for DOnations”计划的一部分来接受捐赠。

介绍 (Introduction)

In complex service-oriented architectures (SOA), programs often need to call multiple services to run through a given workflow. This is fine once everything is in place, but if the code you are working on requires a service that is still in development, you can be stuck waiting for other teams to finish their work before beginning yours. Additionally, for testing purposes you may need to interact with external vendor services, like a weather API or a record-keeping system. Vendors usually don’t give you as many environments as you need, and often don’t make it easy to control test data on their systems. In these situations, unfinished services and services outside of your control can make code testing frustrating.

在复杂的面向服务的体系结构(SOA)中 ,程序通常需要调用多个服务才能在给定的工作流程中运行。 一切就绪后就可以了,但是如果您正在使用的代码需要仍在开发中的服务,则您可能会被困在等待其他团队完成工作之后再开始您的工作。 此外,出于测试目的,您可能需要与外部供应商服务进行交互,例如天气API或记录保存系统。 供应商通常不会为您提供所需的尽可能多的环境,并且往往无法轻松控制其系统上的测试数据。 在这些情况下,未完成的服务和无法控制的服务会使代码测试令人沮丧。

The solution to all of these problems is to create a service mock. A service mock is code that simulates the service that you would use in the final product, but is lighter weight, less complex, and easier to control than the actual service you would use in production. You can set a mock service to return a default response or specific test data, then run the software you’re interested in testing as if the dependent service were really there. Because of this, having a flexible way to mock services can make your workflow faster and more efficient.

解决所有这些问题的方法是创建一个服务模型 。 服务模拟是模拟您将在最终产品中使用的服务的代码,但比您在生产中使用的实际服务更轻巧,更简单,更易于控制。 您可以设置一个模拟服务以返回默认响应或特定的测试数据,然后像运行依赖服务一样运行您要测试的软件。 因此,采用一种灵活的方法来模拟服务可以使您的工作流程更快,更高效。

In an enterprise setting, making mock services is sometimes called service virtualization. Service virtualization is often associated with expensive enterprise tools, but you don’t need an expensive tool to mock a service. Mountebank is a free and open source service-mocking tool that you can use to mock HTTP services, including REST and SOAP services. You can also use it to mock SMTP or TCP requests.

在企业环境中,制作模拟服务有时称为服务虚拟化 。 服务虚拟化通常与昂贵的企业工具相关联,但是您不需要昂贵的工具来模拟服务。 Mountebank是一个免费的开放源代码服务模拟工具,可用于模拟HTTP服务,包括RESTSOAP服务。 您也可以使用它来模拟SMTPTCP请求。

In this guide, you will build two flexible service-mocking applications using Node.js and Mountebank. Both of the mock services will listen to a specific port for REST requests in HTTP. In addition to this simple mocking behavior, the service will also retrieve mock data from a comma-separated values (CSV) file. After this tutorial, you’ll be able to mock all kinds of service behavior so you can more easily develop and test your applications.

在本指南中,您将使用Node.js和Mountebank构建两个灵活的服务模拟应用程序。 两种模拟服务都将侦听HTTP中REST请求的特定端口。 除了这种简单的模拟行为之外,该服务还将从逗号分隔值 (CSV)文件中检索模拟数据。 学习完本教程后,您将能够模拟各种服务行为,从而可以更轻松地开发和测试应用程序。

先决条件 (Prerequisites)

To follow this tutorial, you will need the following:

要遵循本教程,您将需要以下内容:

第1步-启动Node.js应用程序 (Step 1 — Starting a Node.js Application)

In this step, you are going to create a basic Node.js application that will serve as the base of your Mountebank instance and the mock services you will create in later steps.

在此步骤中,您将创建一个基本的Node.js应用程序,它将作为您的Mountebank实例以及在后续步骤中创建的模拟服务的基础。

Note: Mountebank can be used as a standalone application by installing it globally using the command npm install -g mountebank. You can then run it with the mb command and add mocks using REST requests.

注意:通过使用命令npm install -g mountebank全局安装Mountebank,可以将其用作独立应用程序。 然后,您可以使用mb命令运行它,并使用REST请求添加模拟。

While this is the fastest way to get Mountebank up and running, building the Mountebank application yourself allows you to run a set of predefined mocks when the app starts up, which you can then store in source control and share with your team. This tutorial will build the Mountebank application manually to take advantage of this.

尽管这是启动和运行Mountebank的最快方法,但您可以自己构建Mountebank应用程序,以便在应用程序启动时运行一组预定义的模拟,然后将其存储在源代码管理中并与团队共享。 本教程将手动构建Mountebank应用程序以利用此优势。

First, create a new directory to put your application in. You can name it whatever you want, but in this tutorial we’ll name it app:

首先,创建一个新目录以放置您的应用程序。您可以随意命名,但在本教程中,我们将其命名为app

  • mkdir app

    mkdir 应用

Move into your newly created directory with the following command:

使用以下命令进入新创建的目录:

  • cd app

    光盘应用

To start a new Node.js application, run npm init and fill out the prompts:

要启动新的Node.js应用程序,请运行npm init并填写提示:

  • npm init

    npm初始化

The data from these prompts will be used to fill out your package.json file, which describes what your application is, what packages it relies on, and what different scripts it uses. In Node.js applications, scripts define commands that build, run, and test your application. You can go with the defaults for the prompts or fill in your package name, version number, etc.

这些提示中的数据将用于填写您的package.json文件,该文件描述了您的应用程序是什么,它依赖于哪些程序包以及使用了哪些不同的脚本。 在Node.js应用程序中,脚本定义用于构建,运行和测试应用程序的命令。 您可以使用默认的提示或填写软件包名称,版本号等。

After you finish this command, you’ll have a basic Node.js application, including the package.json file.

完成此命令后,您将拥有一个基本的Node.js应用程序,包括package.json文件。

Now install the Mountebank npm package using the following:

现在,使用以下命令安装Mountebank npm软件包:

  • npm install -save mountebank

    npm install-保存mountebank

This command grabs the Mountebank package and installs it to your application. Make sure to use the -save flag in order to update your package.json file with Mountebank as a dependency.

此命令获取Mountebank软件包并将其安装到您的应用程序。 确保使用-save标志,以将Mountebank作为依赖项来更新package.json文件。

Next, add a start script to your package.json that runs the command node src/index.js. This script defines the entry point of your app as index.js, which you’ll create in a later step.

接下来,将一个开始脚本添加到您的package.json ,该脚本运行命令node src/index.js 。 该脚本将应用程序的入口点定义为index.js ,您将在后续步骤中创建它。

Open up package.json in a text editor. You can use whatever text editor you want, but this tutorial will use nano.

在文本编辑器中打开package.json 。 您可以使用所需的任何文本编辑器,但本教程将使用nano。

  • nano package.json

    纳米package.json

Navigate to the "scripts" section and add the line "start": "node src/index.js". This will add a start command to run your application.

导航到"scripts"部分,并添加"start": "node src/index.js" 。 这将添加一个start命令来运行您的应用程序。

Your package.json file should look similar to this, depending on how you filled in the initial prompts:

您的package.json文件应类似于此,具体取决于您如何填写初始提示:

app/package.json
app / package.json
{
  "name": "diy-service-virtualization",
  "version": "1.0.0",
  "description": "An application to mock services.",
  "main": "index.js",
  "scripts": {
    "start": "node src/index.js"
  },
  "author": "Dustin Ewers",
  "license": "MIT",
  "dependencies": {
    "mountebank": "^2.0.0"
  }
}

You now have the base for your Mountebank application, which you built by creating your app, installing Mountebank, and adding a start script. Next, you’ll add a settings file to store application-specific settings.

现在,您已经拥有Mountebank应用程序的基础,该应用程序是通过创建应用程序,安装Mountebank并添加启动脚本而构建的。 接下来,您将添加一个设置文件来存储特定于应用程序的设置。

第2步-创建设置文件 (Step 2 — Creating a Settings File)

In this step, you will create a settings file that determines which ports the Mountebank instance and the two mock services will listen to.

在此步骤中,您将创建一个设置文件,该文件确定Mountebank实例和两个模拟服务将侦听的端口。

Each time you run an instance of Mountebank or a mock service, you will need to specify what network port that service will run on (e.g., http://localhost:5000/). By putting these in a settings file, the other parts of your application will be able to import these settings whenever they need to know the port number for the services and the Mountebank instance. While you could directly code these into your application as constants, changing the settings later will be easier if you store them in a file. This way, you will only have to change the values in one place.

每次运行Mountebank实例或模拟服务时,都需要指定该服务将在哪个网络端口上运行(例如, http://localhost:5000/ )。 通过将它们放置在设置文件中,您的应用程序的其他部分将能够在需要知道服务和Mountebank实例的端口号时导入这些设置。 尽管您可以将它们直接作为常量编码到应用程序中,但是如果将它们存储在文件中,则以后更改设置将更加容易。 这样,您只需要在一个地方更改值即可。

Begin by making a directory called src from your app directory:

首先从您的app目录创建一个名为src的目录:

  • mkdir src

    mkdir src

Navigate to the folder you just created:

导航到您刚刚创建的文件夹:

  • cd src

    光盘src

Create a file called settings.js and open it in your text editor:

创建一个名为settings.js的文件,然后在文本编辑器中将其打开:

  • nano settings.js

    纳米settings.js

Next, add settings for the ports for the main Mountebank instance and the two mock services you’ll create later:

接下来,添加主Mountebank实例的端口设置以及稍后将创建的两个模拟服务:

app/src/settings.js
app / src / settings.js
module.exports = {
    port: 5000,
    hello_service_port: 5001,
    customer_service_port: 5002
}

This settings file has three entries: port: 5000 assigns port 5000 to the main Mountebank instance, hello_service_port: 5001 assigns port 5001 to the Hello World test service that you will create in a later step, and customer_service_port: 5002 assigns port 5002 to the mock service app that will respond with CSV data. If the ports here are occupied, feel free to change them to whatever you want. module.exports = makes it possible for your other files to import these settings.

此设置文件有三项: port: 5000受让人端口5000到主走江湖例如, hello_service_port: 5001受让人端口5001来的Hello World测试服务,您将在后续步骤中创建和customer_service_port: 5002受让人端口5002来模拟将使用CSV数据响应的服务应用。 如果此处的端口已被占用,请随时将其更改为所需的端口。 module.exports =使其他文件可以导入这些设置。

In this step, you used settings.js to define the ports that Mountebank and your mock services will listen to and made these settings available to other parts of your app. In the next step, you will build an initialization script with these settings to start Mountebank.

在此步骤中,您使用settings.js定义了Mountebank和您的模拟服务将侦听的端口,并使这些设置可用于您应用程序的其他部分。 在下一步中,将使用这些设置构建一个初始化脚本来启动Mountebank。

第3步-构建初始化脚本 (Step 3 — Building the Initialization Script)

In this step, you’re going to create a file that starts an instance of Mountebank. This file will be the entry point of the application, meaning that, when you run the app, this script will run first. You will add more lines to this file as you build new service mocks.

在此步骤中,您将创建一个文件来启动Mountebank实例。 该文件将成为应用程序的入口点,这意味着,当您运行应用程序时,该脚本将首先运行。 在构建新的服务模拟时,将向该文件添加更多行。

From the src directory, create a file called index.js and open it in your text editor:

src目录中,创建一个名为index.js的文件,然后在文本编辑器中将其打开:

  • nano index.js

    纳米index.js

To start an instance of Mountebank that will run on the port specified in the settings.js file you created in the last step, add the following code to the file:

要启动将在上一步创建的settings.js文件中指定的端口上运行的Mountebank实例,请在该文件中添加以下代码:

app/src/index.js
app / src / index.js
const mb = require('mountebank');
const settings = require('./settings');

const mbServerInstance = mb.create({
        port: settings.port,
        pidfile: '../mb.pid',
        logfile: '../mb.log',
        protofile: '../protofile.json',
        ipWhitelist: ['*']
    });

This code does three things. First, it imports the Mountebank npm package that you installed earlier (const mb = require('mountebank');). Then, it imports the settings module you created in the previous step (const settings = require('./settings');). Finally, it creates an instance of the Mountebank server with mb.create().

这段代码完成了三件事。 首先,它导入您之前安装的Mountebank npm软件包( const mb = require('mountebank'); )。 然后,它将导入您在上一步中创建的设置模块( const settings = require('./settings'); )。 最后,它使用mb.create()创建Mountebank服务器的实例。

The server will listen at the port specified in the settings file. The pidfile, logfile, and protofile parameters are for files that Mountebank uses internally to record its process ID, specify where it keeps its logs, and set a file to load custom protocol implementations. The ipWhitelist setting specifies what IP addresses are allowed to communicate with the Mountebank server. In this case, you’re opening it up to any IP address.

服务器将侦听设置文件中指定的端口。 pidfilelogfileprotofile参数适用于Mountebank内部使用的文件,用于记录其进程ID,指定其保存日志的位置以及设置文件以加载自定义协议实现。 ipWhitelist设置指定允许哪些IP地址与Mountebank服务器通信。 在这种情况下,您可以将其打开到任何IP地址。

Save and exit from the file.

保存并退出文件。

After this file is in place, enter the following command to run your application:

放置此文件后,输入以下命令以运行您的应用程序:

  • npm start

    npm开始

The command prompt will disappear, and you will see the following:

命令提示符将消失,您将看到以下内容:

  • info: [mb:5000] mountebank v2.0.0 now taking orders - point your browser to http://localhost:5000/ for help

    信息:[mb:5000] mountebank v 2.0.0现在正在接受订单-将浏览器指向http:// localhost:5000 /以获取帮助

This means your application is open and ready to take requests.

这意味着您的应用程序已打开并且可以接受请求。

Next, check your progress. Open up a new terminal window and use curl to send the following GET request to the Mountebank server:

接下来,检查进度。 打开一个新的终端窗口,并使用curl将以下GET请求发送到Mountebank服务器:

  • curl http://localhost:5000/

    卷曲http:// localhost:5000 /

This will return the following JSON response:

这将返回以下JSON响应:


   
   
Output
{ "_links": { "imposters": { "href": "http://localhost:5000/imposters" }, "config": { "href": "http://localhost:5000/config" }, "logs": { "href": "http://localhost:5000/logs" } } }

The JSON that Mountebank returns describes the three different endpoints you can use to add or remove objects in Mountebank. By using curl to send reqests to these endpoints, you can interact with your Mountebank instance.

Mountebank返回的JSON描述了可用于在Mountebank中添加或删除对象的三个不同的端点。 通过使用curl将请求发送到这些端点,您可以与Mountebank实例进行交互。

When you’re done, switch back to your first terminal window and exit the application using CTRL + C. This exits your Node.js app so you can continue adding to it.

完成后,切换回第一个终端窗口,并使用CTRL + C退出应用程序。 这将退出您的Node.js应用程序,因此您可以继续添加它。

Now you have an application that successfully runs an instance of Mountebank. In the next step, you will create a Mountebank client that uses REST requests to add mock services to your Mountebank application.

现在,您有了一个可以成功运行Mountebank实例的应用程序。 在下一步中,您将创建一个使用REST请求将模拟服务添加到您的Mountebank应用程序的Mountebank客户端。

第4步-建立Mountebank客户 (Step 4 — Building a Mountebank Client)

Mountebank communicates using a REST API. You can manage the resources of your Mountebank instance by sending HTTP requests to the different endpoints mentioned in the last step. To add a mock service, you send a HTTP POST request to the imposters endpoint. An imposter is the name for a mock service in Mountebank. Imposters can be simple or complex, depending on the behaviors you want in your mock.

Mountebank使用REST API进行通信。 您可以通过将HTTP请求发送到上一步中提到的不同端点来管理Mountebank实例的资源。 要添加模拟服务,请将HTTP POST请求发送到冒名顶替者端点。 冒名顶替者是Mountebank中模拟服务的名称。 冒名顶替者可以是简单的也可以是复杂的,具体取决于您在模拟中想要的行为。

In this step, you will build a Mountebank client to automatically send POST requests to the Mountebank service. You could send a POST request to the imposters endpoint using curl or Postman, but you’d have to send that same request every time you restart your test server. If you’re running a sample API with several mocks, it will be more efficient to write a client script to do this for you.

在此步骤中,您将构建一个Mountebank客户端,以自动将POST请求发送到Mountebank服务。 您可以使用curl或Postman向冒名顶替者端点发送POST请求,但是每次重新启动测试服务器时都必须发送相同的请求。 如果您正在运行带有多个模拟的示例API,那么编写客户端脚本来为您执行此操作将更加有效。

Begin by installing the node-fetch library:

首先安装node-fetch库:

  • npm install -save node-fetch

    npm install-保存节点获取

The node-fetch library gives you an implementation of the JavaScript Fetch API, which you can use to write shorter HTTP requests. You could use the standard http library, but using node-fetch is a lighter weight solution.

node-fetch为您提供JavaScript Fetch API的实现,可用于编写较短的HTTP请求。 您可以使用标准的http库,但是使用node-fetch是一个轻量级的解决方案。

Now, create a client module to send requests to Mountebank. You only need to post imposters, so this module will have one method.

现在,创建一个客户端模块以将请求发送到Mountebank。 您只需要发布冒名顶替者,因此该模块只有一种方法。

Use nano to create a file called mountebank-helper.js:

使用nano创建一个名为mountebank-helper.js的文件:

  • nano mountebank-helper.js

    纳米mountebank-helper.js

To set up the client, put the following code in the file:

要设置客户端,请在文件中输入以下代码:

app/src/mountebank-helper.js
app / src / mountebank-helper.js
const fetch = require('node-fetch');
const settings = require('./settings');

function postImposter(body) {
    const url = `http://127.0.0.1:${settings.port}/imposters`;

    return fetch(url, {
                    method:'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(body)
                });
}

module.exports = { postImposter };

This code starts off by pulling in the node-fetch library and your settings file. This module then exposes a function called postImposter that posts service mocks to Mountebank. Next, body: determines that the function takes JSON.stringify(body), a JavaScript object. This object is what you’re going to POST to the Mountebank service. Since this method is running locally, you run your request against 127.0.0.1 (localhost). The fetch method takes the object sent in the parameters and sends the POST request to the url.

该代码通过拉入node-fetch库和您的设置文件开始。 然后,此模块公开一个名为postImposter的函数,该函数将服务postImposter发布到Mountebank。 接下来, body:确定函数采用JavaScript对象JSON.stringify(body) 。 这个对象是你打算怎么POST到走江湖的服务。 由于此方法在本地运行,因此您可以针对127.0.0.1 ( localhost )运行请求。 fetch方法获取参数中发送的对象,并将POST请求发送到url

In this step, you created a Mountebank client to post new mock services to the Mountebank server. In the next step, you’ll use this client to create your first mock service.

在此步骤中,您创建了一个Mountebank客户端,以将新的模拟服务发布到Mountebank服务器。 在下一步中,您将使用此客户端创建您的第一个模拟服务。

步骤5 —创建您的第一个模拟服务 (Step 5 — Creating Your First Mock Service)

In previous steps, you built an application that creates a Mountebank server and code to call that server. Now it’s time to use that code to build an imposter, or a mock service.

在前面的步骤中,您构建了一个应用程序,该应用程序创建Mountebank服务器并编写代码以调用该服务器。 现在是时候使用该代码构建冒名顶替者或模拟服务了。

In Mountebank, each imposter contains stubs. Stubs are configuration sets that determine the response that an imposter will give. Stubs can be further divided into combinations of predicates and responses. A predicate is the rule that triggers the imposter’s response. Predicates can use lots of different types of information, including URLs, request content (using XML or JSON), and HTTP methods.

在Mountebank中,每个冒名顶替者都包含存根 。 存根是确定冒名顶替者将做出响应的配置集。 存根可以进一步分为谓词响应的组合。 谓词是触发冒名顶替者React的规则。 谓词可以使用许多不同类型的信息,包括URL,请求内容(使用XML或JSON)和HTTP方法。

Looked at from the point of view of a Model-View-Controller (MVC) app, an imposter acts like a controller and the stubs like actions within that controller. Predicates are routing rules that point toward a specific controller action.

Model-View-Controller(MVC)应用程序的角度来看,冒名顶替者的行为类似于控制器,而存根则类似于该控制器中的动作。 谓词是指向特定控制器操作的路由规则。

To create your first mock service, create a file called hello-service.js. This file will contain the definition of your mock service.

要创建第一个模拟服务,请创建一个名为hello-service.js的文件。 该文件将包含您的模拟服务的定义。

Open hello-service.js in your text editor:

在文本编辑器中打开hello-service.js

  • nano hello-service.js

    纳米hello-service.js

Then add the following code:

然后添加以下代码:

app/src/hello-service.js
app / src / hello-service.js
const mbHelper = require('./mountebank-helper');
const settings = require('./settings');

function addService() {
    const response = { message: "hello world" }

    const stubs = [
        {
            predicates: [ {
                equals: {
                    method: "GET",
                    "path": "/"
                }
            }],
            responses: [
                {
                    is: {
                        statusCode: 200,
                        headers: {
                            "Content-Type": "application/json"
                        },
                        body: JSON.stringify(response)
                    }
                }
            ]
        }
    ];

    const imposter = {
        port: settings.hello_service_port,
        protocol: 'http',
        stubs: stubs
    };

    return mbHelper.postImposter(imposter);
}

module.exports = { addService };

This code defines an imposter with a single stub that contains a predicate and a response. Then it sends that object to the Mountebank server. This code will add a new mock service that listens for GET requests to the root url and returns { message: "hello world" } when it gets one.

这段代码定义了带有单个存根的冒名顶替者,其中包含谓词和响应。 然后,它将对象发送到Mountebank服务器。 这段代码将添加一个新的模拟服务,该服务会监听对根url GET请求,并在GET到该请求时返回{ message: "hello world" }

Let’s take a look at the addService() function that the preceding code creates. First, it defines a response message hello world:

让我们看一下前面的代码创建的addService()函数。 首先,它定义一个响应消息hello world

const response = { message: "hello world" }
...

Then, it defines a stub:

然后,它定义一个存根:

...
        const stubs = [
        {
            predicates: [ {
                equals: {
                    method: "GET",
                    "path": "/"
                }
            }],
            responses: [
                {
                    is: {
                        statusCode: 200,
                        headers: {
                            "Content-Type": "application/json"
                        },
                        body: JSON.stringify(response)
                    }
                }
            ]
        }
    ];
...

This stub has two parts. The predicate part is looking for a GET request to the root (/) URL. This means that stubs will return the response when someone sends a GET request to the root URL of the mock service. The second part of the stub is the responses array. In this case, there is one response, which returns a JSON result with an HTTP status code of 200.

此存根包含两个部分。 谓词部分正在寻找对根( / )URL的GET请求。 这意味着当有人向模拟服务的根URL发送GET请求时, stubs将返回响应。 存根的第二部分是responses数组。 在这种情况下,会有一个响应,该响应返回JSON结果和HTTP状态代码200

The final step defines an imposter that contains that stub:

最后一步定义了包含该存根的冒名顶替者:

...
    const imposter = {
        port: settings.hello_service_port,
        protocol: 'http',
        stubs: stubs
    };
...

This is the object you’re going to send to the /imposters endpoint to create an imposter that mocks a service with a single endpoint. The preceding code defines your imposter by setting the port to the port you determined in the settings file, setting the protocol to HTTP, and assigning stubs as the imposter’s stubs.

这是您要发送到/imposters端点的对象,以创建模仿单个端点的服务的冒名顶替者。 前面的代码通过将port设置为在设置文件中确定的端口,将protocol设置为HTTP,并将stubs分配为冒名顶替的存根,从而定义了冒名顶替者。

Now that you have a mock service, the code sends it to the Mountebank server:

现在您有了模拟服务,代码将其发送到Mountebank服务器:

...
    return mbHelper.postImposter(imposter);
...

As mentioned before, Mountebank uses a REST API to manage its objects. The preceding code uses the postImposter() function that you defined earlier to send a POST request to the server to activate the service.

如前所述,Mountebank使用REST API来管理其对象。 前面的代码使用您先前定义的postImposter()函数向服务器发送POST请求以激活服务。

Once you are finished with hello-service.js, save and exit from the file.

使用hello-service.js完成后,保存并退出文件。

Next, call the newly created addService() function in index.js. Open the file in your text editor:

接下来,在index.js调用新创建的addService()函数。 在文本编辑器中打开文件:

  • nano index.js

    纳米index.js

To make sure that the function is called when the Mountebank instance is created, add the following highlighted lines:

为了确保在创建Mountebank实例时调用该函数,请添加以下突出显示的行:

app/src/index.js
app / src / index.js
const mb = require('mountebank');
const settings = require('./settings');
const helloService = require('./hello-service');

const mbServerInstance = mb.create({
        port: settings.port,
        pidfile: '../mb.pid',
        logfile: '../mb.log',
        protofile: '../protofile.json',
        ipWhitelist: ['*']
    });

mbServerInstance.then(function() {
    helloService.addService();
});

When a Mountebank instance is created, it returns a promise. A promise is an object that does not determine its value until later. This can be used to simplify asynchronous function calls. In the preceding code, the .then(function(){...}) function executes when the Mountebank server is initialized, which happens when the promise resolves.

创建Mountebank实例后,它将返回promise 。 许诺是直到以后才确定其价值的对象。 这可以用来简化异步函数调用。 在前面的代码中, .then(function(){...})函数在初始化Mountebank服务器时执行,该事件在promise解析后发生。

Save and exit index.js.

保存并退出index.js

To test that the mock service is created when Mountebank initializes, start the application:

要测试在Mountebank初始化时是否创建了模拟服务,请启动应用程序:

  • npm start

    npm开始

The Node.js process will occupy the terminal, so open up a new terminal window and send a GET request to http://localhost:5001/:

Node.js进程将占用终端,因此打开一个新的终端窗口并将GET请求发送到http://localhost:5001/

  • curl http://localhost:5001

    卷曲http:// localhost:5001

You will receive the following response, signifying that the service is working:

您将收到以下响应,表示该服务正在运行:


   
   
Output
{"message": "hello world"}

Now that you tested your application, switch back to the first terminal window and exit the Node.js application using CTRL + C.

既然您已经测试了应用程序,请切换回第一个终端窗口并使用CTRL + C退出Node.js应用程序。

In this step, you created your first mock service. This is a test service mock that returns hello world in response to a GET request. This mock is meant for demonstration purposes; it doesn’t really give you anything you couldn’t get by building a small Express application. In the next step, you’ll create a more complex mock that takes advantage of some of Mountebank’s features.

在此步骤中,您创建了第一个模拟服务。 这是一个测试服务模拟程序,它响应GET请求返回hello world 。 该模拟仅用于演示目的。 它实际上并没有提供构建小型Express应用程序无法获得的任何功能。 在下一步中,您将创建一个更复杂的模拟,该模拟将利用Mountebank的某些功能。

第6步-构建数据支持的模拟服务 (Step 6 — Building a Data-Backed Mock Service)

While the type of service you created in the previous step is fine for some scenarios, most tests require a more complex set of responses. In this step, you’re going to create a service that takes a parameter from the URL and uses it to look up a record in a CSV file.

虽然您在上一步中创建的服务类型在某些情况下很好,但是大多数测试都需要更复杂的响应集。 在此步骤中,您将创建一个服务,该服务从URL中获取一个参数,并使用该参数在CSV文件中查找记录。

First, move back to the main app directory:

首先,回到主app目录:

  • cd ~/app

    cd〜/ app

Create a folder called data:

创建一个名为data的文件夹:

  • mkdir data

    mkdir数据

Open a file for your customer data called customers.csv:

打开一个名为customers.csv的客户数据文件:

  • nano data/customers.csv

    纳米数据/customers.csv

Add in the following test data so that your mock service has something to retrieve:

添加以下测试数据,以便您的模拟服务可以检索某些内容:

app/data/customers.csv
app / data / customers.csv
id,first_name,last_name,email,favorite_color 
1,Erda,Birkin,ebirkinb@google.com.hk,Aquamarine
2,Cherey,Endacott,cendacottc@freewebs.com,Fuscia
3,Shalom,Westoff,swestoffd@about.me,Red
4,Jo,Goulborne,jgoulbornee@example.com,Red

This is fake customer data generated by the API mocking tool Mockaroo, similar to the fake data you’d load into a customers table in the service itself.

这是API 模拟工具Mockaroo生成的伪造的客户数据,类似于您将加载到服务本身的customers表中的伪造数据。

Save and exit the file.

保存并退出文件。

Then, create a new module called customer-service.js in the src directory:

然后,在src目录中创建一个名为customer-service.js的新模块:

  • nano src/customer-service.js

    纳米src / customer-service.js

To create an imposter that listens for GET requests on the /customers/ endpoint, add the following code:

要创建在/customers/端点上侦听GET请求的冒名顶替者,请添加以下代码:

app/src/customer-service.js
app / src / customer-service.js
const mbHelper = require('./mountebank-helper');
const settings = require('./settings');

function addService() {
    const stubs = [
        {
            predicates: [{
                and: [
                    { equals: { method: "GET" } },
                    { startsWith: { "path": "/customers/" } }
                ]
            }],
            responses: [
                {
                    is: {
                        statusCode: 200,
                        headers: {
                            "Content-Type": "application/json"
                        },
                        body: '{ "firstName": "${row}[first_name]", "lastName": "${row}[last_name]", "favColor": "${row}[favorite_color]" }'
                    },
                    _behaviors: {
                        lookup: [
                            {
                                "key": {
                                  "from": "path",
                                  "using": { "method": "regex", "selector": "/customers/(.*)$" },
                                  "index": 1
                                },
                                "fromDataSource": {
                                  "csv": {
                                    "path": "data/customers.csv",
                                    "keyColumn": "id"
                                  }
                                },
                                "into": "${row}"
                              }
                        ]
                    }
                }
            ]
        }
    ];

    const imposter = {
        port: settings.customer_service_port,
        protocol: 'http',
        stubs: stubs
    };

    return mbHelper.postImposter(imposter);
}

module.exports = { addService };

This code defines a service mock that looks for GET requests with a URL format of customers/<id>. When a request is received, it will query the URL for the id of the customer and then return the corresponding record from the CSV file.

这段代码定义了一个服务模拟,该服务模拟使用URL格式为customers/<id> GET请求。 收到请求后,它将在URL中查询客户的id ,然后从CSV文件返回相应的记录。

This code uses a few more Mountebank features than the hello service you created in the last step. First, it uses a feature of Mountebank called behaviors. Behaviors are a way to add functionality to a stub. In this case, you’re using the lookup behavior to look up a record in a CSV file:

与您在上一步中创建的hello服务相比,此代码使用了更多的Mountebank功能。 首先,它使用Mountebank的一个名为behaviors的功能。 行为是向存根添加功能的一种方式。 在这种情况下,您正在使用lookup行为来查找CSV文件中的记录:

...
  _behaviors: {
      lookup: [
          {
              "key": {
                "from": "path",
                "using": { "method": "regex", "selector": "/customers/(.*)$" },
                "index": 1
              },
              "fromDataSource": {
                "csv": {
                  "path": "data/customers.csv",
                  "keyColumn": "id"
                }
              },
              "into": "${row}"
            }
      ]
  }
...

The key property uses a regular expression to parse the incoming path. In this case, you’re taking the id that comes after customers/ in the URL.

key属性使用正则表达式解析输入路径。 在这种情况下,您要在URL中使用customers/之后的id

The fromDataSource property points to the file you’re using to store your test data.

fromDataSource属性指向您用来存储测试数据的文件。

The into property injects the result into a variable ${row}. That variable is referenced in the following body section:

into属性将结果注入变量${row} 。 以下body部分引用了该变量:

...
  is: {
      statusCode: 200,
      headers: {
          "Content-Type": "application/json"
      },
      body: '{ "firstName": "${row}[first_name]", "lastName": "${row}[last_name]", "favColor": "${row}[favorite_color]" }'
  },
...

The row variable is used to populate the body of the response. In this case, it’s a JSON string with the customer data.

行变量用于填充响应的正文。 在这种情况下,它是带有客户数据的JSON字符串。

Save and exit the file.

保存并退出文件。

Next, open index.js to add the new service mock to your initialization function:

接下来,打开index.js以将新服务模拟添加到您的初始化函数中:

  • nano src/index.js

    纳米src / index.js

Add the highlighted line:

添加突出显示的行:

app/src/index.js
app / src / index.js
const mb = require('mountebank');
const settings = require('./settings');
const helloService = require('./hello-service');
const customerService = require('./customer-service');

const mbServerInstance = mb.create({
        port: settings.port,
        pidfile: '../mb.pid',
        logfile: '../mb.log',
        protofile: '../protofile.json',
        ipWhitelist: ['*']
    });

mbServerInstance.then(function() {
    helloService.addService();
    customerService.addService();
});

Save and exit the file.

保存并退出文件。

Now start Mountebank with npm start. This will hide the prompt, so open up another terminal window. Test your service by sending a GET request to localhost:5002/customers/3. This will look up the customer information under id 3.

现在通过npm start启动Mountebank。 这将隐藏提示,因此打开另一个终端窗口。 通过将GET请求发送到localhost:5002/customers/3来测试您的服务。 这将在id 3下查找客户信息。

  • curl localhost:5002/customers/3

    curl本地主机:5002 / customers / 3

You will see the following response:

您将看到以下响应:


   
   
Output
{ "firstName": "Shalom", "lastName": "Westoff", "favColor": "Red" }

In this step, you created a mock service that read data from a CSV file and returned it as a JSON response. From here, you can continue to build more complex mocks that match the services you need to test.

在此步骤中,您创建了一个模拟服务,该服务从CSV文件读取数据并将其作为JSON响应返回。 从这里开始,您可以继续构建更复杂的模拟,以匹配需要测试的服务。

结论 (Conclusion)

In this article you created your own service-mocking application using Mountebank and Node.js. Now you can build mock services and share them with your team. Whether it’s a complex scenario involving a vendor service you need to test around or a simple mock while you wait for another team to finish their work, you can keep your team moving by creating mock services.

在本文中,您使用Mountebank和Node.js创建了自己的服务模拟应用程序。 现在,您可以构建模拟服务并将其与您的团队共享。 无论是涉及需要测试的供应商服务的复杂场景,还是等待另一个团队完成工作时的简单模拟,您都可以通过创建模拟服务来保持团队的运转。

If you want to learn more about Mountebank, check out their documentation. If you’d like to containerize this application, check out Containerizing a Node.js Application for Development With Docker Compose. If you’d like to run this application in a production-like environment, check out How To Set Up a Node.js Application for Production on Ubuntu 18.04.

如果您想了解更多有关Mountebank的信息,请查阅其文档 。 如果您想对该应用程序进行容器化,请查看容器化Node.js应用程序以使用Docker Compose进行开发 。 如果您想在生产环境中运行此应用程序,请查看如何在Ubuntu 18.04上为生产设置Node.js应用程序

翻译自: https://www.digitalocean.com/community/tutorials/how-to-mock-services-using-mountebank-and-node-js

mountebank

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值