Convert test data sources to typed TheoryData

Replace untyped MemberData sources with TheoryData<...>, use collection
expressions for array and list literals, drop redundant casts and null
suppressions, and give log-assertion helpers an IsEnabled setup so guarded
log calls stay verifiable.
This commit is contained in:
2026-11-29 21:42:41 +02:00
parent ada3c77778
commit 17774b40b8
31 changed files with 649 additions and 693 deletions
@@ -14,7 +14,7 @@ namespace BatteryMonitor.Manager.Tests;
/// </summary>
internal static class BatteryMonitorTestData
{
public const string DefaultFriendlyName = "Battery Device";
private const string DefaultFriendlyName = "Battery Device";
/// <summary>
/// Describes one entity exposed through <see cref="IHaContext.GetAllEntities"/>.
@@ -79,9 +79,9 @@ internal static class BatteryMonitorTestData
/// <summary>
/// Wires <see cref="IHaContext.GetState"/> and <see cref="IHaContext.GetAllEntities"/>
/// on the mock and returns the created entities in declaration order.
/// on the mock, exposing the entities in declaration order.
/// </summary>
public static IReadOnlyList<Entity> ConfigureHaContext(Mock<IHaContext> haContextMock, params EntitySpec[] entities)
public static void ConfigureHaContext(Mock<IHaContext> haContextMock, params EntitySpec[] entities)
{
var entityList = new List<Entity>(entities.Length);
@@ -96,8 +96,6 @@ internal static class BatteryMonitorTestData
}
haContextMock.Setup(h => h.GetAllEntities()).Returns(entityList);
return entityList;
}
public static BatterySensorInfo CreateSensorInfo(string entityId, double batteryLevel, string? friendlyName = null)
@@ -112,16 +110,12 @@ internal static class BatteryMonitorTestData
public static List<BatterySensorInfo> CreateSensorInfos(params (string EntityId, double BatteryLevel)[] sensors)
{
return sensors
.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel))
.ToList();
return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel))];
}
public static List<BatterySensorInfo> CreateSensorInfos(params (string EntityId, string FriendlyName, double BatteryLevel)[] sensors)
{
return sensors
.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel, s.FriendlyName))
.ToList();
return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel, s.FriendlyName))];
}
/// <summary>
@@ -129,12 +123,14 @@ internal static class BatteryMonitorTestData
/// </summary>
public static EntitySpec[] CreateGeneratedBatteryEntities(int count)
{
return Enumerable.Range(0, count)
.Select(i => Battery(
$"sensor.generated_battery_{i:D3}",
i.ToString(CultureInfo.InvariantCulture),
$"Generated Battery {i:D3}"))
.ToArray();
return
[
.. Enumerable.Range(0, count)
.Select(i => Battery(
$"sensor.generated_battery_{i:D3}",
i.ToString(CultureInfo.InvariantCulture),
$"Generated Battery {i:D3}"))
];
}
/// <summary>
@@ -143,12 +139,14 @@ internal static class BatteryMonitorTestData
/// </summary>
public static IReadOnlyList<BatterySensorInfo> CreateGeneratedSensorInfos(int count)
{
return Enumerable.Range(0, count)
.Select(i => CreateSensorInfo(
$"sensor.generated_{i:D3}",
(i * 37) % 101,
$"Generated Device {i:D3}"))
.ToList();
return
[
.. Enumerable.Range(0, count)
.Select(i => CreateSensorInfo(
$"sensor.generated_{i:D3}",
i * 37 % 101,
$"Generated Device {i:D3}"))
];
}
/// <summary>
@@ -188,8 +186,8 @@ internal static class BatteryMonitorTestData
/// States that must never produce a <see cref="BatterySensorInfo"/>, including
/// whitespace/malformed strings and a null state.
/// </summary>
public static TheoryData<string?> UnusableStateRows { get; } = new()
{
public static TheoryData<string?> UnusableStateRows { get; } =
[
"unavailable",
"unknown",
"UNAVAILABLE",
@@ -202,8 +200,8 @@ internal static class BatteryMonitorTestData
"--1",
"low",
"1 2",
(string?)null
};
null
];
/// <summary>
/// Cross-product of every excluded keyword (lower and upper case) plus
@@ -232,13 +230,5 @@ internal static class BatteryMonitorTestData
}
/// <summary>Device counts used to exercise notification payload generation.</summary>
public static TheoryData<int> NotifyDeviceCounts { get; } = new()
{
1,
2,
3,
5,
10,
50
};
public static TheoryData<int> NotifyDeviceCounts { get; } = [1, 2, 3, 5, 10, 50];
}
@@ -36,9 +36,10 @@ public class BatteryNotificationServiceTests
public void NotifyLowBattery_WithDevices_ShouldCallPersistentNotificationCreate(int deviceCount)
{
var devices = CreateSensorInfos(
Enumerable.Range(0, deviceCount)
.Select(i => ($"sensor.device_{i:D3}", $"Device {i:D3}", (double)(i % 5)))
.ToArray());
[
.. Enumerable.Range(0, deviceCount)
.Select(i => ($"sensor.device_{i:D3}", $"Device {i:D3}", (double)(i % 5)))
]);
var sut = CreateSut();
sut.NotifyLowBattery(devices);
@@ -99,6 +100,7 @@ public class BatteryNotificationServiceTests
[Fact]
public void NotifyLowBattery_WithDevices_ShouldLogDeviceCount()
{
_loggerMock.Setup(l => l.IsEnabled(LogLevel.Information)).Returns(true);
var devices = CreateSensorInfos(
("sensor.a", "Device A", 2),
("sensor.b", "Device B", 3));
@@ -106,17 +108,13 @@ public class BatteryNotificationServiceTests
var sut = CreateSut();
sut.NotifyLowBattery(devices);
_loggerMock.Verify(
l => l.Log(
LogLevel.Information,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((state, _) => string.Equals(
state!.ToString(),
"Sent low battery notification for 2 device(s)",
StringComparison.Ordinal)),
It.IsAny<Exception?>(),
It.IsAny<Func<It.IsAnyType, Exception?, string>>()),
Times.Once);
var logInvocation = _loggerMock.Invocations
.Where(invocation => invocation.Method.Name == nameof(ILogger.Log))
.Should().ContainSingle().Subject;
logInvocation.Arguments[0].Should().Be(LogLevel.Information);
logInvocation.Arguments[2].Should().NotBeNull();
logInvocation.Arguments[2]!.ToString().Should().Be("Sent low battery notification for 2 device(s)");
}
#endregion
@@ -274,7 +272,7 @@ public class BatteryNotificationServiceTests
[Fact]
public void BuildNotificationMessage_WithNoDevices_ShouldContainOnlyHeader()
{
var message = BatteryNotificationService.BuildNotificationMessage(Array.Empty<BatterySensorInfo>());
var message = BatteryNotificationService.BuildNotificationMessage([]);
message.Should().Be("The following devices have low battery:");
message.Should().NotContain("- **");
@@ -12,23 +12,17 @@ namespace BatteryMonitor.Manager.Tests;
public class BatterySensorDiscoveryServiceTests
{
private readonly Mock<IHaContext> _haContextMock;
private readonly Mock<ILogger<BatterySensorDiscoveryService>> _loggerMock;
public BatterySensorDiscoveryServiceTests()
{
_haContextMock = new Mock<IHaContext>();
_loggerMock = new Mock<ILogger<BatterySensorDiscoveryService>>();
}
private readonly Mock<IHaContext> _haContextMock = new();
private readonly Mock<ILogger<BatterySensorDiscoveryService>> _loggerMock = new();
private BatterySensorDiscoveryService CreateSut()
{
return new BatterySensorDiscoveryService(_haContextMock.Object, _loggerMock.Object);
}
private IReadOnlyList<Entity> SetupEntities(params EntitySpec[] entities)
private void SetupEntities(params EntitySpec[] entities)
{
return ConfigureHaContext(_haContextMock, entities);
ConfigureHaContext(_haContextMock, entities);
}
#region Discovery
@@ -139,11 +133,13 @@ public class BatterySensorDiscoveryServiceTests
result.Should().HaveCount(expectedIncluded ? 1 : 0);
if (expectedIncluded)
if (!expectedIncluded)
{
result[0].EntityId.Should().Be("sensor.boundary_battery");
result[0].BatteryLevel.Should().Be(double.Parse(state, CultureInfo.InvariantCulture));
return;
}
result[0].EntityId.Should().Be("sensor.boundary_battery");
result[0].BatteryLevel.Should().Be(double.Parse(state, CultureInfo.InvariantCulture));
}
[Fact]