In this post, we’re going to cover the recent extensions to the DalSoft RestClient library which allows you to easily test a REST API using C#.

This post is aimed at anyone (devs, testers, etc) who tests REST APIs and is suitable for all levels. If you haven’t written a test before though we recommend reading this unit test series. The main focus point of this article will be how to perform system testing on your REST API.

If you haven’t used DalSoft RestClient before you can learn about it by reading this post.

The code examples can found in this GitHub repository.

In this article we will learn:

Let’s get into it.

About System Testing

There are four types of testing: system, integration, unit, and acceptance testing.

The type of testing we’re going to cover in this post is System Testing. System Testing is a form of “Black Box” testing which means testing without knowing anything about the internals of the System Under Test (SUT). It’s usually the last gate before deploying changes into production.

System Testing is usually done on an environment that is as close to production as possible such as a staging or UAT (User Acceptance Testing) environment. Some people even system test using their production environment as part of a continual QA process.

For our example, we are going to test the JSONPlaceholder API.

Let’s start by installing the DalSoft RestClient Package first.

Install the DalSoft RestClient Package

There are two easy ways to do this:

Install via .NET CLI:
dotnet add package DalSoft.RestClient

Or Install via NuGet through the Package Management Console:
Install-Package DalSoft.RestClient

That is all we need in terms of the required libraries.

Optionally Create an “SDK” to Test your REST API

For our example, we are going to create an “SDK” to system test the JSONPlaceholder API. This is optional because we could just use Rest Client’s dynamic features instead.

To create the SDK we are going to make use of Rest Client’s Resource method. To do this all we need to do is create a Resource class. A Resource class has properties and methods returning strings that represent our resources. We then can use the methods and properties in the Resource method as an expression.

Here is an example of our simple SDK:

Use Verify in our System Tests

Now that we have a Resource class, all we need to do to call the JSONPlaceholder API is pass it as a generic parameter to the Resource method along with an expression parameter representing the Resource, and finally, call the HTTP method we want.

This sounds harder than it is and it can all be wrapped up easily in a couple of lines of code:

Now we know we can call the JSONPlaceholder API easily it’s time to write some system tests.

This is easily done using the Verify method.

To use the Verify method you provide a generic parameter to cast your response to (usually either your Model, a string or HttpResponseMessage) and an expression returning a boolean representing the condition you want to verify.

Let’s write some tests.

Verify that the resource /users/1 returns a 200 OK status code:

Verify that the response body of the JSON returned is what we were expecting:

We can do one better. We can verify that the response body can be cast to a User object, and the User object returned is what we expect:

You can also chain the Verify methods together to be nice and “Fluent”:

What Happens if a Verify Test Condition Fails?

So what happens when a Verify test condition fails?

Simple AggregateException is thrown and the InnerExceptions contain a VerifiedFailed exception for each failure because an exception is thrown our test fails. The VerifiedFailed exception contains a descriptive message of exactly what condition failed.

Let’s make our test fail and see what it looks like. Take the last test we did and make it fail:

View live example

Running this test will give you the following output:

System.AggregateException: One or more errors occurred.
(user => (user.Username == "This will Fail") was not verified)
(response => (Convert(response.StatusCode, Int32) == 400) was not verified)

There are more advanced features for handling Verify failures that we will cover later on in the post.

Use DalSoft Rest Client’s Dynamic Features

We mentioned creating the Resource class or “SDK” was optional. This is because if you don’t pass the generic parameter a dynamic object is returned, which you can work with right away!

Here’s how it looks, you can start testing a REST API right away with a few lines of code:

View live example

You may have noticed the strange variable naming in this test, this is because when using a dynamic object you can’t get the full expression in the VerifyFailed exception message. Instead, we only get the parameter name, so naming it like this tells us what failed. For example, if the test above failed it would look like:

System.AggregateException: One or more errors occurred.
(dynamic userIsBret => ... was not verified)
(dynamic httpResponseMessageIsOk => ... was not verified)

You can also mix and match Generic and Dynamic Verify methods:

Fine-Grained Control Using OnVerifyFailed

We’ve covered what happens if a Verify test condition fails earlier and for most testing scenarios this should work fine.

There are advanced options to handle failed verifications, but it’s worth noting these are designed more for validation than testing. For advanced scenarios, we can use the OnVerifyFailed callback to handle failed verifications. By default instead of throwing the OnVerifyFailed callback just passes an AggregateException (containing VerifiedFailed exceptions) and a response object to an Action you provide.

Here’s what it looks like:

View live example

Running the above code your notice that the OnVerifyFailed callback is called and no exceptions are thrown.

Like Verify you can use a generic parameter to cast the response:

You can use the OnVerifyFailed callback to handle and throw by setting the throwOnVerifyFailed parameter to true:

Running the above test will cause OnVerifyFailed to be called and an exception to be thrown.

Where in the chain OnVerifyFailed appears is important. OnVerifyFailed will only handle Verifications above itself in the chain. By default (throwOnVerifyFailed: false) only the first OnVerifyFailed callback will “handle” the failures, and subsequent OnVerifyFailed callbacks in the chain won’t be called.

However, we can use the throwOnVerifyFailed parameter to change this behavior.

In the example below the last invoked OnVerifyFailed callback in the chain decides whether an exception should be thrown. This simply means if the last OnVerifyFailed callback in the chain has Verify failures and throwOnVerifyFailed is true an exception is thrown.

Putting it All Together

Putting all this together gives us fine-grained control over what to do with the Verify failures.

This contrived example shows how to handle individual groups of Verify failures:

View live example

The first OnVerifyFailed callback only handles the Verify failure directly above it in the chain. The next OnVerifyFailed callback in the chain only handles the Verify failure directly above but sets throwOnVerifyFailed to true. This means the last OnVerifyFailed is called for the Verify failure directly above as well as the previous failure. An exception is thrown because the last OnVerifyFailed callback has throwOnVerifyFailed set to true.

Use Rest Client Factory in Your Test Fixture

Creating HttpClient (which Rest Client extends) is expensive. In most cases for system tests, you could use a Static field with a one-time initialized Rest Client. However, it would be better to use HttpClientFactory / RestClientFactory, in a future post, we will explore how to use a Test Fixture with RestClientFactory.

Conclusion

In this post, you’ve learned how to use DalSoft Rest Client to system test a REST API. We built a simple SDK and learned how easy it is to call a REST API right away using Rest Client’s dynamic features.

All the source code for this post is in this GitHub repository.

If you have enjoyed reading this article and if you would like to receive the notifications about the freshly published .NET Core content we encourage you to subscribe to our blog.