C Web Api 2 Check For Dev Test Pod

  • We are grateful for wonderful sponsors who help sustain the DEV Community. Sponsorship Info/Policy. Uploading Profile Pictures in a React and Rails API App Part II. POST Request Welcome to Fiber — an Express.js styled web framework written in Go with ️ I hated Regex so much that I made iHateRegex.io How to.
  • Jul 17, 2014  As a valued partner and proud supporter of MetaCPAN, StickerYou is happy to offer a 10% discount on all Custom Stickers, Business Labels, Roll Labels, Vinyl Lettering or Custom Decals. StickerYou.com is your one-stop shop to make your business stick. Use code METACPAN10 at checkout to apply your discount.
  • Create three instances of ASP.NET Core 3 web API behind a 'load balancer' that will route to any of them on Kubernetes local cluster. Create ASP.NET Core 3 Web API Let's start by creating a new Web API using dotnet new command. Open Git Bash as an administrator and type command which will create a project template in app directory.
  1. C Web Api 2 Check For Dev Test Pods
  2. C Web Api 2 Check For Dev Test Pod Price

Best online Api Tester: it can test your api call. This project is funded and maintained by Caramba.We 💛 open source software! Check out our other open source projects, read our blog or say 👋 on twitter @carambalabs. Contributions are welcome 🤘 We encourage developers like you to help us improve the projects we’ve shared with the community. Please see the Contributing Guide and the Code of Conduct.

-->

by Tom FitzMacken

This guidance and application demonstrate how to create simple unit tests for your Web API 2 application. This tutorial shows how to include a unit test project in your solution, and write test methods that check the returned values from a controller method.

This tutorial assumes you are familiar with the basic concepts of ASP.NET Web API. For an introductory tutorial, see Getting Started with ASP.NET Web API 2.

The unit tests in this topic are intentionally limited to simple data scenarios. For unit testing more advanced data scenarios, see Mocking Entity Framework when Unit Testing ASP.NET Web API 2.

Software versions used in the tutorial

  • Web API 2

In this topic

This topic contains the following sections:

  • Create application with unit test project

Prerequisites

Visual Studio 2017 Community, Professional or Enterprise edition

Download code

Download the completed project. The downloadable project includes unit test code for this topic and for the Mocking Entity Framework when Unit Testing ASP.NET Web API topic.

Create application with unit test project

You can either create a unit test project when creating your application or add a unit test project to an existing application. This tutorial shows both methods for creating a unit test project. To follow this tutorial, you can use either approach.

Add unit test project when creating the application

Create a new ASP.NET Web Application named StoreApp.

In the New ASP.NET Project windows, select the Empty template and add folders and core references for Web API. Select the Add unit tests option. The unit test project is automatically named StoreApp.Tests. You can keep this name.

After creating the application, you will see it contains two projects.

Add unit test project to an existing application

If you did not create the unit test project when you created your application, you can add one at any time. For example, suppose you already have an application named StoreApp, and you want to add unit tests. To add a unit test project, right-click your solution and select Add and New Project.

Select Test in the left pane, and select Unit Test Project for the project type. Name the project StoreApp.Tests.

You will see the unit test project in your solution.

In the unit test project, add a project reference to the original project.

Set up the Web API 2 application

In your StoreApp project, add a class file to the Models folder named Product.cs. Replace the contents of the file with the following code.

Build the solution.

Right-click the Controllers folder and select Add and New Scaffolded Item. Select Web API 2 Controller - Empty.

Set the controller name to SimpleProductController, and click Add.

Replace the existing code with the following code. To simplify this example, the data is stored in a list rather than a database. The list defined in this class represents the production data. Notice that the controller includes a constructor that takes as a parameter a list of Product objects. This constructor enables you to pass test data when unit testing. The controller also includes two async methods to illustrate unit testing asynchronous methods. These async methods were implemented by calling Task.FromResult to minimize extraneous code, but normally the methods would include resource-intensive operations.

The GetProduct method returns an instance of the IHttpActionResult interface. IHttpActionResult is one of the new features in Web API 2, and it simplifies unit test development. Classes that implement the IHttpActionResult interface are found in the System.Web.Http.Results namespace. These classes represent possible responses from an action request, and they correspond to HTTP status codes.

Build the solution.

You are now ready to set up the test project.

Install NuGet packages in test project

When you use the Empty template to create an application, the unit test project (StoreApp.Tests) does not include any installed NuGet packages. Other templates, such as the Web API template, include some NuGet packages in the unit test project. For this tutorial, you must include the Microsoft ASP.NET Web API 2 Core package to the test project.

Right-click the StoreApp.Tests project and select Manage NuGet Packages. You must select the StoreApp.Tests project to add the packages to that project.

Find and install Microsoft ASP.NET Web API 2 Core package.

Close the Manage NuGet Packages window.

Create tests

By default, your test project includes an empty test file named UnitTest1.cs. This file shows the attributes you use to create test methods. For your unit tests, you can either use this file or create your own file.

For this tutorial, you will create your own test class. You can delete the UnitTest1.cs file. Add a class named TestSimpleProductController.cs, and replace the code with the following code.

Run tests

You are now ready to run the tests. All of the method that are marked with the TestMethod attribute will be tested. From the Test menu item, run the tests.

Open the Test Explorer window, and notice the results of the tests.

Summary

You have completed this tutorial. The data in this tutorial was intentionally simplified to focus on unit testing conditions. For unit testing more advanced data scenarios, see Mocking Entity Framework when Unit Testing ASP.NET Web API 2.

-->

by Mike Wasson

This topic describes some specific techniques for unit testing controllers in Web API 2. Before reading this topic, you might want to read the tutorial Unit Testing ASP.NET Web API 2, which shows how to add a unit-test project to your solution.

Software versions used in the tutorial

C Web Api 2 Check For Dev Test Pods

  • Web API 2
  • Moq 4.5.30

Note

I used Moq, but the same idea applies to any mocking framework. Moq 4.5.30 (and later) supports Visual Studio 2017, Roslyn and .NET 4.5 and later versions.

A common pattern in unit tests is 'arrange-act-assert':

  • Arrange: Set up any prerequisites for the test to run.
  • Act: Perform the test.
  • Assert: Verify that the test succeeded.

In the arrange step, you will often use mock or stub objects. That minimizes the number of dependencies, so the test is focused on testing one thing.

Here are some things that you should unit test in your Web API controllers:

  • The action returns the correct type of response.
  • Invalid parameters return the correct error response.
  • The action calls the correct method on the repository or service layer.
  • If the response includes a domain model, verify the model type.

These are some of the general things to test, but the specifics depend on your controller implementation. In particular, it makes a big difference whether your controller actions return HttpResponseMessage or IHttpActionResult. For more information about these result types, see Action Results in Web Api 2.

Testing Actions that Return HttpResponseMessage

Here is an example of a controller whose actions return HttpResponseMessage. Sys_auto_sql_tuning_task 12c.

Notice the controller uses dependency injection to inject an IProductRepository. That makes the controller more testable, because you can inject a mock repository. The following unit test verifies that the Get method writes a Product to the response body. Assume that repository is a mock IProductRepository.

It's important to set Request and Configuration on the controller. Otherwise, the test will fail with an ArgumentNullException or InvalidOperationException.

C Web Api 2 Check For Dev Test Pod Price

Testing Link Generation

The Post method calls UrlHelper.Link to create links in the response. This requires a little more setup in the unit test:

The UrlHelper class needs the request URL and route data, so the test has to set values for these. Another option is mock or stub UrlHelper. With this approach, you replace the default value of ApiController.Url with a mock or stub version that returns a fixed value.

Let's rewrite the test using the Moq framework. Install the Moq NuGet package in the test project.

In this version, you don't need to set up any route data, because the mock UrlHelper returns a constant string.

Testing Actions that Return IHttpActionResult

In Web API 2, a controller action can return IHttpActionResult, which is analogous to ActionResult in ASP.NET MVC. The IHttpActionResult interface defines a command pattern for creating HTTP responses. Instead of creating the response directly, the controller returns an IHttpActionResult. Later, the pipeline invokes the IHttpActionResult to create the response. This approach makes it easier to write unit tests, because you can skip a lot of the setup that is needed for HttpResponseMessage.

Here is an example controller whose actions return IHttpActionResult.

This example shows some common patterns using IHttpActionResult. Let's see how to unit test them.

Action returns 200 (OK) with a response body

The Get method calls Ok(product) if the product is found. In the unit test, make sure the return type is OkNegotiatedContentResult and the returned product has the right ID.

Notice that the unit test doesn't execute the action result. You can assume the action result creates the HTTP response correctly. (That's why the Web API framework has its own unit tests!)

Action returns 404 (Not Found)

The Get method calls NotFound() if the product is not found. For this case, the unit test just checks if the return type is NotFoundResult.

Action returns 200 (OK) with no response body

The Delete method calls Ok() to return an empty HTTP 200 response. Like the previous example, the unit test checks the return type, in this case OkResult.

Action returns 201 (Created) with a Location header

The Post method calls CreatedAtRoute to return an HTTP 201 response with a URI in the Location header. In the unit test, verify that the action sets the correct routing values.

Action returns another 2xx with a response body

The Put method calls Content to return an HTTP 202 (Accepted) response with a response body. This case is similar to returning 200 (OK), but the unit test should also check the status code.

Additional Resources

  • Writing tests for an ASP.NET Web API service (blog post by Youssef Moussaoui).
Comments are closed.