Skip to content

Simple continuous integration with Appveyor and Newman

Posted in Building future-proof software, Productivity, and Tutorials

Last month, I posted about Postman enabling you to test your APIs with little effort so that you can build future-proof software. Here we are going to cover setting up continuous integration for a simple project by using Newman to run your Postman collections. You may have heard about continuous integration in the past. Most commonly, continuous integration will build software from one’s changes before or after merging them into the main codebase. Even though there is an infinity of tools that allow implementing continuous integration, I will focus on Appveyor CI. In order to make things simple, I will create a very basic web API project and will host it on GitHub.

Create GitHub repository

You can create the repository on GitHub by clicking this link: Create a repository on Github. For more details, please follow the documentation they provide on their website.

Big lines, you should see something like this when you create the repository:

Create a repository on GitHub

Once you’re all set, if you have not done it yet, you need to clone your repository. Personally, command-line feels easier as a simple “git clone” will do the job.

git clone <your-repository-address>

Command-line execution will look like this.

Create Web API project

Project setup

Now that your repository is all set, we can actually create the Web API project. For this step, you will need to install Visual Studio, ideally 2017 that you can download here. Once installed, open it and create a new project by selecting “File”, then “New” then “Project”.

After the project template selection popup appears, select “ASP.NET Web Application”. As for the project path, select the one where you cloned your repository and press ok.

Now you will have to select what kind of web application you want to create. Select “Empty” and make sure that the “Web API”  option is enabled like below. Note that selecting “Add unit tests” is not necessary for this tutorial.

Then press “Ok” and wait for the project creation. Once it’s done, your solution explorer should look like this.

Time to add some code. Yeah!

Add your Controller

First, right-click on the “Controllers” folder. Now, select “Add” then “Controller”. Pick “Web API 2 Controller – Empty” and press “Add”.

Next, you get to pick the controller name. Here it will be DivisionController.

Now you should have an empty controller looking like this:

The first project run

From here it’s time to run your project either by pressing F5. Also, you can open the menu and select “Debug” then “Start Debugging”. After a few seconds, a browser window will open and you will see 403 error page.

Chill, it’s perfectly normal as no method in our DivisionController is defined and access to your project directory is limited by default. At this point, we can already open Postman and create our first test.

It’s Postman time!

The first test

Now, open Postman, create a new tab. Once the tab created, copy the URL opened by Visual Studio debugger in Chrome. In my case, it’s “http://localhost:53825” but yours could be different. Paste that URL in your postman tab like this:

Next, press “Send” and you shall see the Postman version of the result we observed previously in Chrome.

From here, we can start writing tests that will define our API behavior for the default endpoint that does not exist yet. Here you can notice a couple of things that we will want to change. First, we don’t want that ugly HTML message to be displayed by default but something a little more friendly. I guess a “Hello Maths!” message is friendlier, from a certain point of view. Let’s add a test for that.

If you remember the previous article, you know that you are supposed to go to the tests tab in order to add it. In this case, will pick the “Response body: Is equal to a string” snippet. You should get some code generated as below:

Next, you will update it to replace “response_body_string” with “Hello Maths!”.

Now that the response test is sorted, let’s add a response code test to validate we should not get that 403 HTTP code. For this, we will use the “Status code: Code is 200” test snippet.

After sending the request again you can see that both tests failed.

Fix the API to make the tests pass

It is now time to write some code to right this wrong. Go back to Visual Studio to modify the DivisionController. We will add an Index method that will return the message we want to see.

[HttpGet]
[Route("")]
public HttpResponseMessage Index()
{
    var response = Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new StringContent("Hello Maths!", Encoding.UTF8, "text/plain");
    return response;
}

This code basically creates a new response object with a status code OK (200) that we want to get. In this object, we add a StringContent object that contains our “Hello Maths!” message. Let’s run the Visual Studio solution again pressing “F5”.

As you can see, the horrible HTML error page has gone now and we see the “Hello Maths!” greeting. Now, if you run that same request in Postman you will see that now our tests pass.

Now save the request in a new collection that we will call “CalculatingWebApiAppveyor” as below.

You should see in the right tab the newly created collection along with the request we just saved.

Implement the division

If you got this far, you’ve done great already unlike our API doesn’t do much yet. It’s time to make it useful. From here, we will add a Divide action that will take in parameter a dividend and a divisor then return the quotient.  You can copy the code below and add it to your controller.

[HttpGet]
[Route("divisions/dividends/{dividend}/divisors/{divisor}/_result")]
public IHttpActionResult Divide(int dividend, int divisor)
{
    return Ok(dividend / divisor);
}

You may notice that the code looks simpler than for “Hello Maths!”. Actually, we could have returned simply return Ok(“Hello Maths!”). However, this would have returned “Hello Maths!” with the quotes for which our test would not have passed. Now, let’s run the project again and add a test for that division endpoint in Postman.

Test the Division

What we want to do is to make sure that our division endpoint actually returns the result of a division. What we will test here is that for 10 divided by 2 we do get 5. From there, you know that the route to be tested will be “divisions/dividends/10/divisors/2/_result”.  Now, create a new tab in Postman and copy the URL from your greetings endpoint. Then, append the route to be tested as below.

Next, we are going to use the “Response body: Is equal to string” snippet to validate that 10 divided by 2 should return 5. Also, we will add a status check just because.

If you followed all the steps correctly you should see both tests passed and the response is indeed 5.

Now, save that last request as “Validate division works” in the CalculatingWebApiAppveyor collection you created.

Finally, you can run your whole collection and you will see all the tests pass green.

Congratulations! You have a fully functional API as long as divisors are different from zero with its own Postman collection. A collection that you can run whenever you like to make sure your API is fine. The one issue though is that you may not be working alone nor want to run Postman whenever you push a change on GitHub.

There is a way to solve this issue and that’s where Appveyor comes into play. But first, let’s commit and push our changes.

Commit and push your code changes

If you haven’t done it yet, it’s time to commit your changes and push them to your Github repository. First, create a new file named .gitignore. More information about what that file does here.

I personally used the Powershell New-Item command but there is an infinity of ways to do that.

New-Item .gitignore

Then, open this .gitignore file that is the default one to use for Visual Studio projects, copy the contents into the file you created.

Now you can commit, push your changes and eventually move on to Appveyor thanks to a few commands. Note that you must run these commands from the directory where your solution and .gitignore are.

# This line make git aware of the files you want to commit
git add .

# This line generates a commit containing your changes
git commit -am "Project ready for CI"

# This line pushes your changes to GitHub
git push

Once these commands executed you should see your solution with the files created on GitHub.

Get your continuous integration swag on

Create an Appveyor CI account

This is probably the simplest part of this tutorial. Simply go to the Appveyor login page, yes login. From here you can log in with a variety of source control related accounts but pick GitHub.

Once logged in you should land on an empty projects dashboard.

Connect your repository to Appveyor CI

Simply press “New Project” and you will be prompted with a list of repositories you have on your GitHub account.

Select “CalculatingWebApiAppveyor” and press “Add”. After a few seconds, you should see this:

To see how it works, press “New build”. What happens next is that Appveyor will download your source code from Github. Then, your source will be compiled, and if there are unit tests in your solution they will be run. But for now, you will see something like this:

Are you surprised? Are you entertained? Because I am. Don’t panic it’s a benign error caused by the fact that Appveyor does not restore a project’s Nuget packages by default. To get rid of that error, go to the settings tab, then to “Build”.

Scroll down until you see the “Before script option”, enable it by selecting “PS”. Now, a text box should appear for you to input nuget restore  like below:

Now, press the “Save” button below and go back to your build dashboard and press “New build” again. If everything goes according to plan you should end up with this:

Congratulations again! You now know at to set up a .NET project on Appveyor.

This is more or less where I would have stopped if I went with my original decision of making this tutorial a two-parter. Since it would not make much sense to stop here considering what’s left we can move on our Postman collection again.

Setup Newman on Appveyor

Create environments

Now that our project, collection, and continuous integration tools are setup, it is time to put our collection to a better use. An automated use. To do so, we will need to update our collection so that it can be run both locally and on Appveyor. In order to achieve that, we will extract the host URLs from our requests and place them in environment files. One we will use locally, the other one on Appveyor.

First, we will create our localhost and Appveyor environments. I will name mine CalculatingWebApiLocalhost and CalculatingWebApiAppveyor. If you don’t remember how to create environments and modify collections to use their variables I happen to have written a post about it. You need at least the requests host to be extracted in the collections.

Your localhost should contain the URL you used so far. Your Appveyor one will be “http://localhost”.  Once done, you should have two environments that each should look like this:

Localhost environment
Appveyor environment

Now your environments are ready, update your collection requests as below.

Greetings request update
Division request update

From here, you can open the collection runner to make sure your collection still works and tests still pass.

Save your collection and environment to your project

It’s time to introduce you to Postman exporting feature because you will now need to move your collection and Appveyor environment to your project. First, let’s export the collection, click on your collection menu button.

After pressing “Export”, you should see this:

Make sure that “Collection v2” is selected then press “Export” again. Now, save the collection in your solution folder.

Next, we will export the Appveyor environment. Go to the “Manage environments” menu, then click on the “Download environment” icon for CalculatingWebApiAppveyor.

Then, save your environment to your solution folder.

The last step, not the least commit and push your changes. Here is a reminder here:

# This line make git aware of the files you want to commit
git add .

# This line generates a commit containing your changes
git commit -am "Add Postman collection and environment"

# This line pushes your changes to GitHub
git push

Now our repository is all set! Let’s get back to Appveyor.

Setup Newman on Appveyor

First, go to the Tests tab:

Then, enter these lines after selecting “PS” on the “After tests script” textbox:

npm install -s -g --unicode=false newman

newman run --disable-unicode .\CalculatingWebApiAppveyor.postman_collection.json -e .\CalculatingWebApiAppveyor.postman_environment.json

The first line installs Newman on your Appveyor container, prevents the dependencies warnings and adapts the execution display to Appveyor. The second executes your collection using the environment you created and also adapts the execution display to Appveyor. If you used different filenames for your collection and environment, please update the command to match them. You should have something like this:

Now, go back to the “Latest build” tab and click on “New build”.

After a few moments, you will see that your build will fail.

Here you can see that Newman actually tells you what went wrong. All your tests failed, and there was a connection error for each of your collection requests. If your build fails for different reasons, you may want to go a few steps back and try again. But if your failed build looks like the capture above, you’re good to go.

Setup local deployment on Appveyor

Yes, we are very close to finishing setting up our Postman based continuous integration system. Now, we need to tell Appveyor that we want to package our solution and deploy it locally so that we can run our collections against it.

First, we will enable IIS locally. IIS is a service that allows running any kind of .NET web apps or APIs, even though it does not limit to it. To enable IIS, go to the “Environment” settings tab, then click on “Add service” and select “Internet Information Services (IIS)”.

After saving your changes, you will go to the “Build” tab and enable the “Package Web Applications for Web Deploy” option and save again.

That option will generate a zip package that will have the same name as your Appveyor project. What we need to do next is to configure Appveyor to deploy that package on the local IIS. In order to do so, we will go to the “Deployment” tab.

Click on “Add deployment” and select “Local Build Server”. Afterward, we will need to add some settings to tell Appveyor where and how to deploy. To do so, press “Add setting” three times then fill each setting to match these values:

  • CalculatingWebApiAppveyor.deploy_website: true
  • CalculatingWebApiAppveyor.site_name: Default Web Site
  • CalculatingWebApiAppveyor.port: 80

Now, you should see something like this:

Remember the Powershell script we added in the “Test” section of the settings, we will need to put it in the “After deployment script” instead. If we don’t do that, the build will always fail since it will try to run our integration tests before locally deploying our application. I will put it here again in case you don’t feel like scrolling up a bit.

npm install -s -g --unicode=false newman

newman run --disable-unicode .\CalculatingWebApiAppveyor.postman_collection.json -e .\CalculatingWebApiAppveyor.postman_environment.json

If you followed everything your “Deployment” settings tab should look like this:

Don’t forget to save your changes and to update your “Tests” tab. Now, your “Tests” settings tab should look like that again:

After saving it, go back to “Latest build” and press “New Build”. Then, you will see that everything simply works.

Well done!

What’s next ?

Now that you know how to setup Newman powered API tests on Appveyor using GitHub, you can chill and call it a day. However, you can also show off your mastery of CI by adding your project badge to your README file.

Note that Appveyor allows you to deploy only when you push commits to your repository, whether it is a direct push or a pull request being merged. Nevertheless, if you have a private Appveyor account you can enable an option to allow local deployment to run your API tests even on pull requests.

Thanks for reading, I hope you enjoyed reading this as much as I enjoyed writing. Also, I would like to shout out a big thanks to Postman labs for featuring my previous post in their favorites of March, that was a really nice surprise.

Good luck helping to make this world fuller of future-proof software every day!

NB: If you don’t feel like creating the Web Api project and that you scrolled straight to the end of the post to get the sources, help yourself.

One Comment

    Leave a Reply

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    %d bloggers like this: