Integration Test with Postman in Azure DevOps Pipeline: Part 1
Tags: azure, postman, devops, pipeline
Published: 2021-04-25 17:32:22

Postman is one of great tool to test our Web API. We use it quite often while developing Web APIs, and we can also use it as integration test in Azure DevOps pipeline.

In this article, I create Web API and postman test script.

# Create sample Web API

We can use any language to develop our Web API, but I use .NET 5 C# as that's my favorite. You can use your own.

```shell
dotnet new webapi -n mywebapi
cd mywebapi
dotnet run
```
After the app is running, I can consume the Web API via postman.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1c4i16rza66q50tx0ioh.png)

# Write Postman Tests

Let's create simple Tests. You can refer to [Postman Test Script Examples](https://learning.postman.com/docs/writing-scripts/script-references/test-examples/) to get examples of test scripts.

1\. Click Tests tab.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uophycbsz1e6e10avp7f.png)

2\. Add following code snippet. 

```javascript
var jsonResponse = pm.response.json();
console.log(jsonResponse);
```

3\. Click "Send" to run both request and test. We can see the output in **Console** which you can find on the bottom left.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sawidugb9lf0rjmrxup2.png)

4\. Update the test script to include **pm.test** and **pm.expect**.

```javascript
var jsonResponse = pm.response.json();
pm.test("5 results are returned", () => {
    pm.expect(jsonResponse).to.have.lengthOf(5);
});
``` 
5\. Send request and confirm the result in **Test Results** pane.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3m3ebf2cn75un6ekvdh6.png)
 
# Save to postman collection

We can use collection to have multiple request/response and test as one set.

1\. Click "Save As" in Save menu.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/snl0y0xbhq7sxilqfrk8.png)

2\. Enter name and add it to existing or new collection.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3le4n54c4teblmepf24j.png)
 
3\. Now it's in the collection.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kvokfie77ckmn826yeor.png)

# Update Web API to support OData

Before adding more tests, let's update existing Web API to support OData.

1\. Go back to solution and add [Microsoft.AspNetCore.OData] package. I use version 7.5.7.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6yjfh6ceg18x27py214m.png)

2\. Add **Microsoft.AspNetCore.Mvc.NewtonsoftJson** too.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ena369e3cbcmw6f0bjwq.png)
 
3\. Update ConfigureServices in Startup.cs and resolve usings.

```csharp
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers().AddNewtonsoftJson(opt =>
    {
        opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    });

    services.AddOData();
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "mywebapi", Version = "v1" });
    });
}
```
4\. Also update app.UseEndpoints section in Configure method.

```csharp
app.UseEndpoints(endpoints =>
{
    endpoints.EnableDependencyInjection();
    endpoints.Select().MaxTop(100).Filter().OrderBy();
    endpoints.MapODataRoute("odata", "odata", GetEdmModel());
    endpoints.MapControllers();
});
```

5\. Add GetEdmModel method.

```csharp
private static IEdmModel GetEdmModel()
{
    ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
    var weatherForecast = builder.EntitySet<WeatherForecast>("WeatherForecast");
    builder.EnableLowerCamelCase();
    return builder.GetEdmModel();
}
```

6\. Change WeatherForecastController.cs to inherit from ODataController.

```csharp
public class WeatherForecastController : ODataController
```

7\. Add **[EnableQuery]** attribute to Get method.

```csharp
[HttpGet]
[EnableQuery]
public IEnumerable<WeatherForecast> Get()
{
    var rng = new Random();
    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateTime.Now.AddDays(index),
        TemperatureC = rng.Next(-20, 55),
        Summary = Summaries[rng.Next(Summaries.Length)]
    })
    .ToArray();
}
```
8\. Update WeatherForecast.cs to have Id property.

```csharp
public class WeatherForecast
{
    public int Id { get; set; }

    public DateTime Date { get; set; }

    public int TemperatureC { get; set; }

    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

    public string Summary { get; set; }
}
```
9\. Make sure it's compile successfully.

# Update existing test

As I added OData support, let's update existing test.

1\. Select "Get WeatherForecast" from the collection and update request URL.

```shell
https://localhost:5001/odata/WeatherForecast
```

2\. Send request and you see the test failed. This is because returned result is different from before.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0s8lmo60tuc6tbycmox8.png)

3\. Update the script.

```javascript
var jsonResponse = pm.response.json();
pm.test("5 results are returned", () => {
    pm.expect(jsonResponse.value).to.have.lengthOf(5);
});
``` 

4\. Send the request again and confirm it works. Save once you confirmed it.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/railndlnpudlb48q2wqr.png)
 
# Add more tests

Go back to postman and add a couple of more tests with OData query.

1\. Click [+] tab and enter following request.

```shell
https://localhost:5001/odata/WeatherForecast?$select=id,summary
```

2\. Add following script to Tests tab. This evaluates if all of the returned objects has field id and summary.

```javascript
var jsonResponse = pm.response.json();
pm.test("All entities have id and summary fields", () => {
    jsonResponse.value.all((value)=>
        pm.expect(value).to.have.keys('id','summary'));
});
pm.test("Http status 200", () => {
    pm.response.to.have.status(200);
});
```

3\. Send request see the result.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1atw43sgluipuc444amz.png) 

4\. Save it to the collection.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5a3kq5ibp4j90w1sio7v.png)
 
5\. Add another request as below.
 
```shell
https://localhost:5001/odata/WeatherForecast?$top=1
```

6\. Add Tests script.

```javascript
var jsonResponse = pm.response.json();
pm.test("1 results are returned", () => {
    pm.expect(jsonResponse.value).to.have.lengthOf(1);
});

pm.test("Http status 200", () => {
    pm.response.to.have.status(200);
});
```

7\. Confirm the result and save it to the collection.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6obir3oxb5td636dtjjj.png)
 
# Summary

In this article, I created OData enabled Web API with .NET 5 and created three tests by using postman. In the next article, I will explain how to run the test from CUI so that we can run it in DevOps pipeline. 

[Next article](https://dev.to/kenakamu/integration-test-with-postman-in-azure-devops-pipeline-part-2-nfk)