www.apress.com

18/03/26

Xamarin Development for the Mac - Testing the REST Client

By Dawid Borycki

Now, when we have the REST client class implemented we can verify its functionality. Because we already know how to write unit tests, we can test the client class automatically. To create unit tests for UsersServiceClientHelper, I start with a new Unit Test App template and change its name to Users. MobileClient.Tests. Then, I edit references such that Users.MobileClient.Tests references the Users.MobileClient project. Subsequently, under the test app, I add a new file, UsersServiceHelperTests.cs, in which I import the following namespaces: System.Linq, System.Threading.Tasks, NUnit.Framework, and Users.MobileClient.Helpers. Then, I declare the UsersServiceHelperTests class as shown in Listing 9.

Listing 1. A Test Class for the UsersServiceHelper

[TestFixture]
public  class  UsersServiceHelperTests

To define the UsersServiceHelperTests class, I first create two private members, shown in Listing 2. The first one, UserId, is a field that stores a default user identifier I will use to validate the Get and Update methods. The second one is a private function, GetUserCount, which calculates the number of elements in a collection of users received from the REST API.

Listing 2.  Private Members of UsersServiceHelperTest

private const int UserId = 5;
private async Task<int> GetUserCount()
{
 
    return (await UsersServiceHelper.Get()).Count();
}

Given the preceding private members, I write the first test method, VerifyGet, which validates the number of elements returned by the REST API (Listing 3). From the JSONPlaceholder website, I know that the Users resource has ten elements. So, in the VerifyGet method, I compare this expected value to that returned by the GetUserCount helper from Listing 2.

Listing 3.  Testing a Get Method by Verifying the Number of Returned Elements

[Test]
public async void VerifyGet()
{

    // Arrange
    const int expectedDataCount = 10;
// Act and Assert
Assert.AreEqual(expectedDataCount, await GetUserCount());
}

Next, I implement another test method, VerifyGetById, shown in Listing 4. This function checks whether two selected public properties of the user retrieved from the REST API possess expected values. Here, I only check the Name and Email properties of the user with identifier 5.

Listing 4. Validating Selected Properties of the User Object Retrieved from the REST API

[Test]
public  async  void  VerifyGetById()
{

    // Arrange
    const  string  expectedName  =  "Chelsey  Dietrich";
    const string expectedEmail = "Lucio_Hettinger@annie.ca";
// Act
var  user  =  await  UsersServiceHelper.Get(UserId);

// Assert
Assert.AreEqual(expectedName, user.Name); Assert.AreEqual(expectedEmail,  user.Email);
}

After writing test methods for the Get functions of the UsersServiceHelper, I implement another

two tests, which are shown in Listings 5 and 6. The first one, VerifyDelete, checks if the number of elements in the Users resource will be decremented after removing one item. To that end, I first read the number of users and store it in the currentDataCount variable. Then, I delete the user of ID 5 and get the user count again. Finally, I check if the actual user count was indeed decremented.

Listing 5.  Checking if the Delete Method Reduces the Number of Users in the Web Service

[Test]
public async void VerifyDelete()
{

    // Arrange
    var  currentDataCount  =  await  GetUserCount(); var     expectedDataCount = currentDataCount - 1;

    // Act
    await     UsersServiceHelper.Delete(UserId); var      actualDataCount  =  await  GetUserCount();

    // Assert
    Assert.AreEqual(expectedDataCount,    actualDataCount);
}

The second method, VerifyUpdate, is used to check whether the UsersServiceHelper.Update

method changes the properties of the selected user object in the web service. So, I first get the user of ID 5 and then change its Name property to that stored in the expectedName constant. Then, I invoke the UsersServiceHelper.Update method to request that the web service update the selected user, and then I retrieve the data of this object. Given that user, I read its Name property to see if it was indeed changed as expected. If not, an appropriate assertion will be raised.

Listing 6. Validating an Update Method by Checking if It Indeed Changes the Name of the User in the Web Service

[Test]

public async void VerifyUpdate()
{

    // Arrange
    const string expectedName = "New name";
    var  user  =  await  UsersServiceHelper.Get(UserId);
// Act
// Update name of the user and then get the user again from the API user.Name = expectedName;
await  UsersServiceHelper.Update(user);
user  =  await  UsersServiceHelper.Get(UserId);
// Assert
// Check if the name of user was indeed updated Assert.AreEqual(expectedName, user.Name);
}

Given the preceding test methods, I run the Users.MobileService.Tests app in the simulator, and then I execute all four tests. Figure 1 features the test app running and the results of our unit tests. We see that only two test methods, VerifyGet and VerifyGetById, were successful. This is because the DELETE and PUT HTTP requests sent to the JSONPlaceholder REST API were faked. The service only returns the OK HTTP status code but does not modify the underlying data. Hence, this functionality will also not work in the mobile client we are going to write. However, we still can modify the data locally and assume that it is correctly updated in the web service.

New Content Item

Figure 1. Unit testing the UsersServiceHelper class

About the Author:

Dawid Borycki is a software engineer, biomedical researcher, and an expert in several Microsoft developer technologies. He has resolved a broad range of software development challenges for device prototypes (mainly medical equipment), embedded device interfacing, and desktop and mobile programming. Dawid regularly speaks at international developers conferences and has published, cited, and presented on numerous developer topics.This article is excerpted from his book Beginning Xamarin Development for the Mac (December 2017).

Want more? Pick up Dawid's book, Beginning Xamarin Development for the Mac, now available on Apress.com.