Sunday, February 11, 2024

Unit testing cheat sheet (xUnit, FakeItEasy, FluentAssertions)

Summary: Samples of C# code handling common unit testing tasks using xUnit, FakeItEasy, and FluentAssertions frameworks.

Here are some tips, samples, and suggestions for implementing common unit testing tasks.

Unit test without parameters:

[Fact]
void SampleClassName_MethodToBeTested_DescriptiveTestTitle()
{
    // ARRANGE
    // ACT
    // ASSERT
}

Unit test with parameters:

[Theory]
[InlineData("abc", 1, true)]
[InlineData("xyz", 2, false)]
void SampleClassName_MethodToBeTested_DescriptiveTestTitle
(
    string? param1,
    int? param2,
    bool? param3
)
{
    // ARRANGE
    // ACT
    // ASSERT
}

Unit tests with DateTime or DateTimeOffset parameters:

[Theory]
[InlineData("2024-06-05 23:45:10.456", "3/28/2007 12:13:50 PM -07:00")]
void SampleClassName_MethodToBeTested_DescriptiveTestTitle
(
    string? paramDateTime,
    string? paramDateTimeOffset
)
{
    DateTime dateTime = DateTime.Parse(paramDateTime);
    DateTime dateTimeOffset = DateTimeOffset.Parse(paramDateTimeOffset);
    ...
}

Unit tests with complex parameters:

[Theory]
[InlineData("{\"id\":123,\"email\":\"joe.doe@somemail.com\",\"enabled\":true}")]
void SampleClassName_MethodToBeTested_DescriptiveTestTitle
(
    string? paramUser
)
{
	// This example uses Newtonsoft.Json, but the same can be done
    // using the default framework's JSON serializer.
    User? user = JsonConvert.DeserializeObject<User?>(paramUser);
    
    // NOTE: Yes, I know about MemberData, but this seems more straightforward IMHO.
    ...
}

Fake object with the default constructor (can use an interface or a class):

ISample fakeISample = A.Fake<ISample>();
Sample fakeSample = A.Fake<Sample>();
ISample<AnotherSample> fakeGenericSample = A.Fake<ISample<AnotherSample>>();

Fake object with a parametrized constructor:

Sample fakeSample = A.Fake<Sample>(x => x.WithArgumentsForConstructor(new object[] { "param1", 2, true }));

Fake returns specific object properties:

User user = A.Fake<User>();

A.CallTo(() => user.Id).Returns(12345);
A.CallTo(() => user.Email).Returns("joe.doe@somemail.com");
A.CallTo(() => user.Enabled).Returns(true);

Fake returns a specific value from a method:

// Data service is used by user service to get user from database
// and we are faking it.
IDataService dataService = A.Fake<IDataService>();

// Define properties of the user object to be retuned.
int id = 12345;

// Let's assume that the method of the UserService class being tested 
// internally calls the GetUserById method of the IDataService object
// (we're using a fake here to simulate a valid return).
A.CallTo(() => dataService.GetUserById(id)).Returns(new User(id));

// UserService is the class we're testing (system under test or SUT).
UserService userService = new UserService(dataService);

// We are testing the Enable method and expect it to be successful.
userService.Enable(id);

Use wildcard to trigger a fake method result for any parametetr value:

// A.<T>_ is a shortcut for a wildcard.
A.CallTo(() => dataService.GetUserById(A<string>._)).Returns(existingUser);

Fake returns a specific value from an async method:

IDataService dataService = A.Fake<IDataService>();

// Define properties of the user object to be retuned.
int id = 12345;

// Assume that GetUserById is an async method returning Task<User>.
A.CallTo(() => dataService.GetUserById(A<string>._)).Returns(Task.FromResult(new User(id)));

Fake returns a specific value from a generic method:

// Data service is used by user service to get user from database
// and we are faking it.
IDataService dataService = A.Fake<IDataService>();

// Define properties of the user object to be retuned.
int id = 12345;

// Data service has a generic method GetUser that we want to fake.
A.CallTo(dataService).Where(call => call.Method.Name == "GetUser")
   .WithReturnType<User>()
   .Returns(new User(id));
   
// UserService is the class we're testing (system under test or SUT).
UserService userService = new UserService(dataService);

Tested method throws an exception of the exact type:

Assert.Throws<InvalidInputException>(
    () => userService.UpdateUser(AzureServiceType.B2C, _id, user, _caller));

Tested method throws any exception derived from the specified type:

Assert.ThrowsAny<InvalidInputException>(
    () => userService.UpdateUser(AzureServiceType.B2C, _id, user, _caller));

Assign expected exception to a variable:

Exception ex = Assert.Throws<InvalidInputException>(
    () => userService.UpdateUser(AzureServiceType.B2C, _id, user, _caller));

Set up a fake SendGrid call:

ISendGridClient _sendGridClient = A.Fake<ISendGridClient>();

System.Net.Http.HttpResponseMessage httpResponse = new();
System.Net.Http.HttpContent         httpContent  = httpResponse.Content;
System.Net.Http.HttpResponseHeaders httpHeaders  = httpResponse.Headers;

httpHeaders.Add("X-Message-Id", "12345");

SendGrid.Response sendGridResponse = 
    A.Fake<SendGrid.Response>(x => x
        .WithArgumentsForConstructor(new object[] { httpStatusCode, httpContent, httpHeaders }));

A.CallTo(() =< _sendGridClient
    .SendEmailAsync(A<SendGridMessage>._, A<CancellationToken>._))
    .Returns(Task.FromResult(sendGridResponse));

Mock HttpContext for a controller class under test:

System.Net.Http.HttpRequest httpRequest = A.Fake<HttpRequest>();
System.Net.Http.HttpContext httpContext= A.Fake<HttpContext>();

A.CallTo(() => httpContext.Request).Returns(httpRequest);

// Set up the request properies that you need.
A.CallTo(() => httpRequest.Scheme).Returns("https");
A.CallTo(() => httpRequest.Host).Returns(new HostString("localhost:8888"));
A.CallTo(() => httpRequest.PathBase).Returns(new PathString("/api/v1"));
A.CallTo(() => httpRequest.Path).Returns(new PathString("sample"));

// SampleController is derived from the ControllerBase class.
SampleController controller = new(...);

controller.ControllerContext =  new ControllerContext()
{
	HttpContext = httpContext
};

Controller method POST returns HTTP status code 201 Created:

// Assume that all dependencies have been set.
ActionResult<User> actionResult = controller.CreateUser(user);

// First, test action result.
actionResult.Should().NotBeNull();
actionResult.Result.Should().NotBeNull();
actionResult.Result.Should().BeOfType<CreatedResult>();

// Next, test response specific result.
CreatedResult? result = actionResult.Result as CreatedResult;

result.Should().NotBeNull();

// Successful POST must return the URL of the GET method 
// ending with the ID of the newly created object in the
// Location header.
result?.Location.Should().NotBeNull();
result?.Location.Should().EndWith(id);

// Finally, check the created object to be returned to consumer.
result?.Value?.Should().NotBeNull();
result?.Value?.Should().BeOfType<User>();

Controller method POST returns HTTP status code 400 Bad Request:

// Assume that all dependencies have been set.
ActionResult<h;User> actionResult = controller.CreateUser(user);

// First, test action result.
actionResult.Should().NotBeNull();
actionResult.Result.Should().NotBeNull();
actionResult.Result.Should().BeOfType<BadRequestObjectResult>();

// Next, test response specific result.
BadRequestObjectResult? result = actionResult.Result as BadRequestObjectResult;

result.Should().NotBeNull();

// Finally, check the error object to be returned to consumer.
// This example shows a custom problem details object ErroDetails,
// which may be different in your case.
result?.Value.Should().NotBeNull();
result?.Value.Should().BeOfType<ErrorDetails>();

if (result?.Value is ErrorDetails errorDetails)
{
    // ServiceCodeType is a custom enum value returned via the error object's 
    // ServiceCode property (this check may be different in your case).
    errorDetails.ServiceCode.Should().NotBeNull();  
    errorDetails.ServiceCode.Should().Be(ServiceCodeType.BadRequest.ToString());
}

Controller method POST returns HTTP status code 401 Unauthorized:

// Assume that all dependencies have been set.
ActionResult<h;User> actionResult = controller.CreateUser(user);

// First, test action result.
actionResult.Should().NotBeNull();
actionResult.Result.Should().NotBeNull();
actionResult.Result.Should().BeOfType<UnauthorizedObjectResult>();

// Next, test response specific result.
UnauthorizedObjectResult? result = actionResult.Result as UnauthorizedObjectResult;

result.Should().NotBeNull();

// Finally, check the error object to be returned to consumer.
// This example shows a custom problem details object ErroDetails,
// which may be different in your case.
result?.Value.Should().NotBeNull();
result?.Value.Should().BeOfType<ErrorDetails>();

if (result?.Value is ErrorDetails errorDetails)
{
    // ServiceCodeType is a custom enum value returned via the error object's 
    // ServiceCode property (this check may be different in your case).
    errorDetails.ServiceCode.Should().NotBeNull();  
    errorDetails.ServiceCode.Should().Be(ServiceCodeType.Unauthorized.ToString());
}

Controller method POST returns HTTP status code 409 Conflict:

// Assume that all dependencies have been set.
ActionResult<h;User> actionResult = controller.CreateUser(user);

// First, test action result.
actionResult.Should().NotBeNull();
actionResult.Result.Should().NotBeNull();
actionResult.Result.Should().BeOfType<ConflictObjectResult>();

// Next, test response specific result.
ConflictObjectResult? result = actionResult.Result as ConflictObjectResult;

result.Should().NotBeNull();

// Finally, check the error object to be returned to consumer.
// This example shows a custom problem details object ErroDetails,
// which may be different in your case.
result?.Value.Should().NotBeNull();
result?.Value.Should().BeOfType<ErrorDetails>();

if (result?.Value is ErrorDetails errorDetails)
{
    // ServiceCodeType is a custom enum value returned via the error object's 
    // ServiceCode property (this check may be different in your case).
    errorDetails.ServiceCode.Should().NotBeNull();  
    errorDetails.ServiceCode.Should().Be(ServiceCodeType.Conflict.ToString());
}

Mock AppSettings:

// The following dictionary mimics appsettings.json file.
// Notice how array values must be defined using indexes.
Dictionary<string,string?> configSettings = new()
{
    {"ServiceA:ValueSettingX", "ValueX"},
    {"ServiceA:ValueSettingY", "ValueY"},
    {"ServiceA:ValueSettingZ", "ValueZ"},
    {"ServiceA:ArraySetting1:0", "Value0"},
    {"ServiceA:ArraySetting1:1", "Value1"},
    {"ServiceA:ArraySetting1:2", "Value2"},
}

IConfiguration config = new ConfigurationBuilder()
    .AddInMemoryCollectionconfigSettings)
    .Build();

Common FluentAssertions:

// Value should not be null.
value.Should().NotBeNull();

// Value should be of specific type.
value.Should().BeOfType<User>();

// Value should be equal to.
value.Should().Be(1);
value.Should().Be(true);
value.Should().Be("expected value");

// Value should contain (comparison is case sensitive).
value.Should().Contain("value");

// Value should contain any one of the specified values (comparison is case sensitive):
value.Should().ContainAny("value1", "value2");

// Value should contain all of the specified values (comparison is case sensitive):
value.Should().ContainAll("value1", "value2");

// String value should be equal to (comparison is case insensitive).
value.Should().BeEquivalentTo("Value");

No comments:

Post a Comment