Refactor services to use DI for IHaContext and TimeProvider

This commit is contained in:
2026-07-03 12:15:44 +03:00
parent 7f280bea7b
commit 2706a6b188
23 changed files with 146 additions and 374 deletions
-141
View File
@@ -1,141 +0,0 @@
# Test Fixes Applied
## Issues Encountered
### Issue 1: Entities.Sensor Property (Moq Limitation)
```
System.NotSupportedException: Unsupported expression: e => e.Sensor
Non-overridable members (here: Entities.get_Sensor) may not be used in setup / verification expressions.
```
### Issue 2: Entity.EntityId Property (Moq Limitation)
```
System.NotSupportedException: Unsupported expression: e => e.EntityId
Non-overridable members (here: Entity.get_EntityId) may not be used in setup / verification expressions.
```
### Issue 3: NullReferenceException (Reflection Error)
```
System.NullReferenceException: Object reference not set to an instance of an object.
at field!.SetValue(sut, nordPoolPrice)
```
**Cause**: Used `GetField` instead of `GetProperty` - `NordPoolPrice` is a property, not a field.
## Root Cause
The Home Assistant code generator creates `Entities`, `Services`, and `Entity` classes with **non-virtual properties**. Moq (the mocking framework) requires properties to be virtual to create mock setups. This is a common limitation when working with generated code.
## Solution Applied
### Before (Broken)
```csharp
private readonly Mock<Entities> _entitiesMock;
private readonly Mock<Services> _servicesMock;
public NordPoolInitTests()
{
_entitiesMock = new Mock<Entities>(_haContextMock.Object);
_servicesMock = new Mock<Services>(_haContextMock.Object);
}
private NordPoolInit CreateSut()
{
// This fails because Entities.Sensor is not virtual
_entitiesMock.Setup(e => e.Sensor)
.Returns(new SensorEntities(_haContextMock.Object));
//...
}
```
### After (Fixed)
#### Fix 1: Use Real Instances for Entities and Services
```csharp
private Entities _entities;
private Services _services;
public NordPoolInitTests()
{
// Use REAL instances of generated classes
_entities = new Entities(_haContextMock.Object);
_services = new Services(_haContextMock.Object);
}
private NordPoolInit CreateSut()
{
return new NordPoolInit(
_haContextMock.Object,
_entities, // Real instance
_services, // Real instance
_loggerMock.Object,
_mapperMock.Object,
_entityManagerMock.Object
);
}
```
#### Fix 2: Use Real Entity Instance in Tests
```csharp
// Before (Broken)
var existingEntity = new Mock<Entity>(_haContextMock.Object, "sensor.test_sensor");
existingEntity.Setup(e => e.EntityId).Returns("sensor.test_sensor");
// After (Fixed)
// Use a real Entity instance (can't mock because EntityId is not virtual)
var existingEntity = new NumericSensorEntity(_haContextMock.Object, "sensor.test_sensor");
```
#### Fix 3: Use GetProperty Instead of GetField
```csharp
// Before (Broken) - NordPoolPrice is a property, not a field
var field = typeof(NordPoolInit).GetField("NordPoolPrice",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
field!.SetValue(sut, nordPoolPrice); // field is null!
// After (Fixed)
var property = typeof(NordPoolInit).GetProperty("NordPoolPrice",
System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
property!.SetValue(sut, nordPoolPrice);
```
## Trade-offs
### ✅ Advantages
- Tests now work with generated Home Assistant classes
- More realistic testing since we're using actual instances
- No need to mock non-virtual properties
### ⚠️ Limitations
- Cannot mock service method calls (e.g., `GetPricesForDateAsync`)
- Full integration test for `InitializeAsync` was removed
- Tests rely on the generated classes behaving consistently
## Test Suite Status
### ✅ Working Tests (18 total)
- ✅ All price calculation tests
- ✅ All time quarter index tests
- ✅ All entity management tests
- ✅ All data parsing tests
- ✅ Constructor and GetCurrentPrice tests
### ⚠️ Removed Test
- ❌ `InitializeAsync_ShouldCallAllNecessaryMethods` - Requires mocking generated service classes
## Alternative Solutions (Future)
1. **Integration Tests**: Create integration tests that run against a real Home Assistant test instance
2. **Interface Wrapper**: Wrap generated classes in interfaces that can be mocked
3. **Partial Testing**: Test individual methods that make up `InitializeAsync` separately (current approach)
## Recommendations
The current solution is pragmatic and works well for unit testing. For comprehensive testing of the full initialization flow, consider:
1. **Add integration tests** with a real Home Assistant instance in Docker
2. **Test individual methods** that `InitializeAsync` calls (GetPricesAsync, EnsureNordPoolEntityExistsAsync, etc.)
3. **Use manual testing** for the full flow during development
---
**Status**: ✅ All tests compile and are ready to run in Rider
**Build Status**: 0 Errors, 0 Warnings
+2 -1
View File
@@ -73,7 +73,8 @@ public class NordPoolInitTests
_schedulerMock.Object,
_cheapestIntervalsFinderMock.Object,
_boilerConfigProviderMock.Object,
options);
options,
TimeProvider.System);
}
[Fact]
-93
View File
@@ -1,93 +0,0 @@
# NordPool.Manager.Tests
This project contains comprehensive unit tests for the `NordPoolInit` class.
## Test Coverage
### Price Calculation Tests
- **PriceCorrection_ShouldCalculateCorrectPrice**: Tests the price conversion from MW/h to cents/kWh with various inputs
- **PriceCorrection_ShouldApplyVatAndConversion**: Validates the full calculation chain (MW to kW, VAT application, Euro to cents conversion)
- **AdjustedNordPoolPrice_ShouldApplyPriceCorrectionToAllPrices**: Ensures price correction is applied to all price entries
- **AdjustedNordPoolPrice_WithNullPriceValue_ShouldSkipThatPrice**: Tests handling of null prices in the list
- **AdjustedNordPoolPrice_WithNullPricesList_ShouldReturnEmptyPricesList**: Tests handling of null price lists
- **AdjustedNordPoolPrice_ShouldPreserveDateTimes**: Ensures start/end times are preserved during price adjustment
### Time Quarter Index Tests
- **GetTimeQuarterIndex_ShouldReturnCorrectIndex**: Tests quarter calculation for various times
- **GetTimeQuarterIndex_ShouldHandleAllHoursCorrectly**: Validates all hours including edge cases (midnight, 23:00, etc.)
### Entity Management Tests
- **GetInitEntitiesList_ShouldReturnFourEntities**: Validates that all required entities are created
- **GetInitEntitiesList_ShouldHaveCorrectEntityProperties**: Ensures entities have correct domain, identifier, and names
- **EnsureNordPoolEntityExistsAsync_WhenEntityDoesNotExist_ShouldCreateEntity**: Tests entity creation when entity is missing
- **EnsureNordPoolEntityExistsAsync_WhenEntityExists_ShouldNotCreateEntity**: Ensures no duplicate entities are created
### Data Parsing Tests
- **ParseNordPoolResult_WithNullElement_ShouldReturnEmptyNordPoolPrice**: Tests null handling
- **ParseNordPoolResult_WithValidElement_ShouldMapCorrectly**: Validates JSON deserialization and mapping
### Integration Tests
- **InitializeAsync_ShouldCallAllNecessaryMethods**: Tests the full initialization flow
- **GetCurrentPrice_WithValidPriceAtIndex_ShouldReturnCorrectPrice**: Tests current price retrieval logic
## Test Framework and Libraries
- **xUnit**: Primary testing framework
- **Moq**: Mocking framework for dependencies
- **FluentAssertions**: Fluent assertion library for readable tests
- **AutoMapper**: Used in the actual implementation, mocked in tests
## Running the Tests
### Using .NET CLI
```bash
dotnet test
```
### Using Rider or Visual Studio
Run tests through the built-in test explorer.
### With Coverage
```bash
dotnet test --collect:"XPlat Code Coverage"
```
## Test Organization
Tests are organized by functionality:
1. **Constructor Tests**: Basic initialization
2. **Calculation Tests**: Price conversion and adjustments
3. **Time Tests**: Quarter index calculations
4. **Entity Tests**: Entity creation and management
5. **Parsing Tests**: JSON parsing and data mapping
6. **Integration Tests**: Full workflow tests
## Mocking Strategy
The tests use Moq to mock all external dependencies:
- `ILogger<NordPoolInit>`: Logging functionality
- `IMapper`: AutoMapper for DTO to model mapping
- `IEntityManager`: Entity management in Home Assistant
- `IHaContext`: Home Assistant context
- `Entities` and `Services`: Home Assistant generated entities and services
## Constants Used in Production Code
The tests validate these constants:
- `MegawattToKilowattDivisor = 1000.0`
- `VatRate = 1.21` (21% VAT)
- `EuroToCentsMultiplier = 100.0`
- `PriceDecimalPlaces = 2`
## Private Method Testing
Some private methods are tested using reflection to ensure internal logic correctness:
- `GetTimeQuarterIndex`
- `PriceCorrection`
- `AdjustedNordPoolPrice`
- `ParseNordPoolResult`
- `GetInitEntitiesList`
- `GetCurrentPrice`
- `EnsureNordPoolEntityExistsAsync`
This approach ensures comprehensive coverage of the business logic while maintaining encapsulation.