Skip to content

Commit

Permalink
Replace ILogger.Moq NuGet with custom class
Browse files Browse the repository at this point in the history
  • Loading branch information
sdepouw committed Mar 8, 2024
1 parent 965bbec commit eada5b7
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,67 +2,67 @@
using DevBetterWeb.Core.Interfaces;
using DevBetterWeb.Infrastructure.Services;
using Microsoft.Extensions.Logging;
using Moq;
using NSubstitute;
using Xunit;
using FluentAssertions;

namespace DevBetterWeb.UnitTests.Infrastructure.Services;

public class JsonParserServiceTests
{
private readonly IJsonParserService _jsonParserService;
private readonly Mock<ILogger<JsonParserService>> _logger = new Mock<ILogger<JsonParserService>>();
private readonly ILogger<JsonParserService> _logger = Substitute.For<ILogger<JsonParserService>>();

public JsonParserServiceTests()
{
this._jsonParserService = new JsonParserService(this._logger.Object);
this._jsonParserService = new JsonParserService(this._logger);
}

[Fact]
public void Parse_InvalidJson_ThrowsJsonException()
{
string invlaidJson = JsonSerializer.Serialize(new { Name = "Test" }).TrimEnd('}');
string invalidJson = JsonSerializer.Serialize(new { Name = "Test" }).TrimEnd('}');

Assert.ThrowsAny<JsonException>(() => this._jsonParserService.Parse(invlaidJson));
Assert.ThrowsAny<JsonException>(() => this._jsonParserService.Parse(invalidJson));
}

[Fact]
public void Parse_ValidJson_WorksAsExpected()
{
string vlaidJson = JsonSerializer.Serialize(new { Name = "Test" });
var expectedResult = JsonDocument.Parse(vlaidJson);
string validJson = JsonSerializer.Serialize(new { Name = "Test" });
var expectedResult = JsonDocument.Parse(validJson);

var actualResult = this._jsonParserService.Parse(vlaidJson);
var actualResult = this._jsonParserService.Parse(validJson);

expectedResult.Should().BeEquivalentTo(actualResult, opt => opt.ComparingByMembers<JsonElement>());
}

[Fact]
public void Parse_InvalidJson_LogsErrorMessage()
{
string invlaidJson = JsonSerializer.Serialize(new { Name = "Test" }).TrimEnd('}');
string invalidJson = JsonSerializer.Serialize(new { Name = "Test" }).TrimEnd('}');

try
{
var actualResult = this._jsonParserService.Parse(invlaidJson);
var actualResult = this._jsonParserService.Parse(invalidJson);

Check warning

Code scanning / CodeQL

Useless assignment to local variable Warning test

This assignment to
actualResult
is useless, since its value is never read.
}
catch (JsonException ex)
{
// The act is throwing an error. It's intercepted, because we need to test the logging.
Assert.NotNull(ex);
this._logger.ReceivedLogError(1, ex, $"Failed JSON parsing for: {invalidJson}");
}

this._logger.VerifyLog(l => l.LogError($"Failed JSON parsing for: {invlaidJson}"));
this._logger.VerifyLog(l => l.LogInformation("JSON parsing has failed"));
this._logger.ReceivedLogInformation(1, "JSON parsing has failed");
}

[Fact]
public void Parse_ValidJson_LogsSuccessInfoMessage()
{
string vlaidJson = JsonSerializer.Serialize(new { Name = "Test" });
var expectedResult = JsonDocument.Parse(vlaidJson);
string validJson = JsonSerializer.Serialize(new { Name = "Test" });

var actualResult = this._jsonParserService.Parse(vlaidJson);
this._jsonParserService.Parse(validJson);

this._logger.VerifyLog(l => l.LogInformation("JSON parsing is successful"));
this._logger.ReceivedLogInformation(1, "JSON parsing is successful");
}
}
30 changes: 30 additions & 0 deletions tests/DevBetterWeb.UnitTests/NSubstituteLoggerExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System;
using Microsoft.Extensions.Logging;
using NSubstitute;

namespace DevBetterWeb.UnitTests;

/// <summary>
/// Extension methods to help verify calls to <see cref="ILogger"/>'s various extension methods
/// that cannot be mocked/verified through normal means.
/// </summary>
internal static class NSubstituteLoggerExtensions
{
/// <summary>
/// Use when you want to verify that <see cref="LoggerExtensions.LogInformation(Microsoft.Extensions.Logging.ILogger,Microsoft.Extensions.Logging.EventId,System.Exception?,string?,object?[])"/>
/// was called <paramref name="numberOfCalls"/> time(s) and with what message you expect.
/// </summary>
public static void ReceivedLogInformation(this ILogger mockedLogger, int numberOfCalls, string expectedMessage)
{
mockedLogger.Received(numberOfCalls).Log(LogLevel.Information, Arg.Any<EventId>(), expectedMessage);
}

/// <summary>
/// Use when you want to verify that <see cref="LoggerExtensions.LogError(Microsoft.Extensions.Logging.ILogger,Microsoft.Extensions.Logging.EventId,System.Exception?,string?,object?[])"/>
/// was called <paramref name="numberOfCalls"/> time(s) and with what excpetion and message you expect.
/// </summary>
public static void ReceivedLogError(this ILogger mockedLogger, int numberOfCalls, Exception expectedException, string expectedMessage)
{
mockedLogger.Received(numberOfCalls).Log(LogLevel.Error, Arg.Any<EventId>(), expectedException, expectedMessage);
}
}

0 comments on commit eada5b7

Please sign in to comment.