Unittest with RestSharp

We’re developing an aspnet core website with webapi backend all on a cloud platform. The auth part is implemented with openidconnect and cookies. Every tab is a new application to reduce release and test times. For the website / applications we have a razor class library that contains the main layout. See all posts in this series cloudnative

Our adapters use IRestClient that is injected during construction. Only using the interface is hard, since it is very limited. Ease of use is with the extension methods, but needs some extra setup. The magic is in the SetupRestClient helper method that configures the use of json and returns the response (with data) constructed with the GetContent* helper methods. Below an example for testing the get of 6 records.

using RestSharp;    // see https://restsharp.dev
using AutoMoqCore;  // see https://github.com/thomashfr/AutoMoqCore

private static void SetupRestclient(AutoMoqer autoMoqer, RestResponse response)
{
  var defaultSerializer = new SerializerConfig();
  defaultSerializer.UseDefaultSerializers();
  var serializers = new RestSerializers(defaultSerializer);
  var fakeClient = autoMoqer.GetMock<IRestClient>();
  fakeClient.SetupGet(x => x.Serializers).Returns(serializers);
  fakeClient.Setup(x => x.ExecuteAsync(
    It.IsAny<RestRequest>(),
    It.IsAny<CancellationToken>()))
  .ReturnsAsync(response);
}

private static string GetContentFor6Records()
{
  var items = Enumerable.Repeat(new Record(), 6);
  return JsonSerializer.Serialize(items);
}

[TestMethod]
public async Task GetRecords_returns_6_items()
{
  var autoMoqer = new AutoMoqer();
  // arrange
  SetupRestclient(autoMoqer, new RestResponse { Content = GetContentFor6Records() });
  //act
  var testObject = autoMoqer.Create<RecordApiAdapter>();
  // assert
  var items = await testObject.GetRecords();
  Assert.AreEqual(6, items.Length);
}
Unknown's avatar

About erictummers

Working in a DevOps team is the best thing that happened to me. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Development and tagged , . Bookmark the permalink.

Leave a comment

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