13.01.2025

Heute habe ich das Problem mit den Health-Check-Tests gelöst. Ich habe einfach ein MockService in den Tests erstellt, um den eigentlichen Service nachzuahmen. Dieses Mock konnte ich dann im eigentlichen Unit-Test nutzen. So musste ich nicht den eigentlichen Service importieren und nutzen.

namespace Buhler.Alm.Workflow.WorkItemWorkflows.Tests.Mocks
{
    using System;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;

    using Microsoft.Extensions.Diagnostics.HealthChecks;

    public class MockHealthCheckService : HealthCheckService
    {
        private readonly HealthStatus _status;

        public MockHealthCheckService(HealthStatus status)
        {
            _status = status;
        }

        public override Task<HealthReport> CheckHealthAsync(Func<HealthCheckRegistration, bool> predicate, CancellationToken cancellationToken = default)
        {
            var report = new HealthReport(
                new Dictionary<string, HealthReportEntry>(),
                _status,
                TimeSpan.FromMilliseconds(1));

            return Task.FromResult(report);
        }
    }
}

namespace Buhler.Alm.Workflow.WorkItemWorkflows.Tests
{
    using Mocks;

    /// <summary>
    /// Contains unit tests for the <see cref="HealthCheck"/> class.
    /// </summary>
    [TestClass]
    public class HealthCheckTest
    {
        /// <summary>
        /// Tests that the HealthCheck service can be initialized without throwing any exceptions.
        /// </summary>
        [TestMethod]
        public void InitializeService()
        {
            var act = () => new HealthCheck(new MockHealthCheckService(HealthStatus.Healthy));
            act.Should().NotThrow();
        }

        /// <summary>
        /// Tests that RunAsync returns an OK result with "Healthy" status when the health check service reports healthy status.
        /// </summary>
        /// <returns>A <see cref="Task"/> representing the asynchronous test operation.</returns>
        [TestMethod]
        public async Task RunAsync_WhenHealthy_ReturnsOkWithHealthyStatus()
        {
            // Arrange
            var mockService = new MockHealthCheckService(HealthStatus.Healthy);
            var context = new Mock<FunctionContext>();
            var request = new MockHttpRequestData(context.Object, new Uri("https://buhler-alm-we-workflows-staging.azurewebsites.net"));
            var function = new HealthCheck(mockService);

            // Act
            var result = await function.RunAsync(request).ConfigureAwait(false);

            // Assert
            result.Should().BeOfType<OkObjectResult>()
                .Which.Value.Should().Be("Healthy");
        }

        /// <summary>
        /// Tests that RunAsync returns an OK result with "Unhealthy" status when the health check service reports unhealthy status.
        /// </summary>
        /// <returns>A <see cref="Task"/> representing the asynchronous test operation.</returns>
        [TestMethod]
        public async Task RunAsync_WhenUnhealthy_ReturnsOkWithUnhealthyStatus()
        {
            // Arrange
            var mockService = new MockHealthCheckService(HealthStatus.Unhealthy);
            var context = new Mock<FunctionContext>();
            var request = new MockHttpRequestData(context.Object, new Uri("https://buhler-alm-we-workflows-staging.azurewebsites.net"));
            var function = new HealthCheck(mockService);

            // Act
            var result = await function.RunAsync(request).ConfigureAwait(false);

            // Assert
            result.Should().BeOfType<OkObjectResult>()
                .Which.Value.Should().Be("Unhealthy");
        }
    }
}

Nachdem ich mit dem fertig war, habe ich meine Lösung noch in meine Lerndokumentation aufgenommen. Es war schön mal wieder ein Erfolgserlebnis zu haben.

Zuletzt aktualisiert