Application Layer Test Coverage Improvement¶
Summary¶
This document tracks the progress of improving Application Layer test coverage with comprehensive unit tests for command/query handlers.
Initial State (Before Improvement)¶
- Total Tests: 32
- Coverage: Only repository port contracts tested
- Handler Tests: 0 (zero handlers tested!)
- Gap: 70 handlers with no tests across 7 bounded contexts
Current State (After Completion of ALL Bounded Contexts - 100% Coverage!)¶
- Total Tests: 887 (+855 new tests, 2772% increase from initial 32)
- Handler Tests: 790 tests covering business logic orchestration
- Test Success Rate: 100% (all 887 tests passing)
- Product Handlers: ✅ 100% Complete (11 of 11 handlers fully tested)
- Manufacturing Handlers: ✅ 100% Complete (10 of 10 handlers fully tested)
- Statistics Handlers: ✅ 100% Complete (11 of 11 handlers fully tested)
- System Handlers: ✅ 100% Complete (14 of 14 handlers fully tested)
- Robots Handlers: ✅ 100% Complete (8 of 8 handlers fully tested)
- WorkPieceCarriers Handlers: ✅ 100% Complete (7 of 7 handlers fully tested)
- Parameters Handlers: ✅ 100% Complete (9 of 9 handlers fully tested)
Handlers Analyzed¶
Total handlers in Application Layer: 70 handlers across 7 bounded contexts:
| Bounded Context | Handlers | Tests Created | Status |
|---|---|---|---|
| Products | 11 | 112 (11 handlers) | ✅ Complete (100% coverage) |
| Manufacturing | 10 | 106 (10 handlers) | ✅ Complete (100% coverage) |
| Statistics | 11 | 133 (11 handlers) | ✅ Complete (100% coverage) |
| System | 14 | 136 (14 handlers) | ✅ Complete (100% coverage) |
| Robots | 8 | 83 (8 handlers) | ✅ Complete (100% coverage) |
| WorkPieceCarriers | 7 | 107 (7 handlers) | ✅ Complete (100% coverage) |
| Parameters | 9 | 113 (9 handlers) | ✅ Complete (100% coverage) |
Manufacturing Handlers - Detailed Coverage¶
✅ Fully Tested (10 handlers - 100% Complete!)¶
- CreateManufacturingProcessHandler - 18 tests (Complex orchestration handler)
- Constructor validation (6 tests for all dependencies)
- Command validation (9 tests: OrderNumber, SerialNumber, WpcId validation)
- Successful process creation with UID generation
- Service orchestration (UID generation, Order/Serial services)
- Repository and UnitOfWork interaction verification
- Orchestration order verification
- Error propagation (Repository, OrderSerialService, UnitOfWork failures)
-
Theory-based scenario tests
-
UpdateProcessStateHandler - 14 tests (State transition handler)
- Constructor validation (3 tests)
- Process not found handling
- State transitions (NotStarted -> InProgress, InProgress -> Completed, InProgress -> Failed, NotStarted/InProgress -> Cancelled)
- NOK reason validation for Failed state
- Default reason for Cancelled state without reason
- Already in target state handling
- Orchestration order verification
-
Error propagation tests
-
CompleteProcessHandler - 10 tests
- Constructor validation (3 tests)
- Process not found handling
- Auto-start process if NotStarted
- Complete InProgress process
- Repository and UnitOfWork verification
- Orchestration order verification
- Error handling (Repository, UnitOfWork failures)
-
Multiple process ID scenarios
-
FailProcessHandler - 11 tests
- Constructor validation (3 tests)
- NOK reason validation (empty, whitespace, null)
- Process not found handling
- Auto-start process if NotStarted then fail
- Fail InProgress process
- Repository and UnitOfWork verification
- Orchestration order verification
- Error handling (Repository, UnitOfWork failures)
-
Theory-based NOK reason scenarios
-
GetActiveProcessesHandler - 8 tests (Query handler)
- Constructor validation (2 tests)
- Default pagination handling
- Custom pagination parameter passing
- Empty collection handling
- Multiple processes retrieval
- Theory-based pagination scenarios
- Cancellation token support
-
Error propagation
-
GetProcessesByWpcIdHandler - 8 tests (Query handler)
- Constructor validation (2 tests)
- Process retrieval by WPC ID
- Repository parameter verification
- Empty collection handling
- Multiple processes for single WPC
- Theory-based WPC ID scenarios
- Cancellation token support
-
Error propagation
-
GetProcessByIdHandler - 9 tests (Query handler)
- Constructor validation (2 tests)
- Successful process retrieval
- Process not found handling (KeyNotFoundException)
- No null return verification
- Repository call verification
- Theory-based process ID scenarios
- Cancellation token support
- Error propagation
-
Multiple calls verification
-
GetProcessByOrderNumberHandler - 9 tests (Query handler)
- Constructor validation (2 tests)
- Successful process retrieval by order number
- Process not found handling (KeyNotFoundException)
- No null return verification
- Repository call verification
- Theory-based order number scenarios
- Cancellation token support
- Error propagation
-
Multiple calls verification
-
UpdateManufacturingProcessHandler - 9 tests
- Constructor validation (3 tests)
- Process not found handling
- Successful process update
- Repository and UnitOfWork verification
- Orchestration order verification
- Process existence check before update
- Theory-based process ID scenarios
-
Error handling (Repository, UnitOfWork failures)
-
DeleteManufacturingProcessHandler - 10 tests
- Constructor validation (3 tests)
- Process not found handling
- Successful process deletion
- Repository and UnitOfWork verification
- Orchestration order verification
- Process existence check before deletion
- No deletion attempt when not found
- Theory-based process ID scenarios
- Error handling (Repository, UnitOfWork failures)
Product Handlers - Detailed Coverage¶
✅ Fully Tested (11 handlers - 100% Complete!)¶
- CreateProductHandler - 11 tests
- Constructor validation
- Successful creation with valid request
- Duplicate name detection (business rule)
- Repository interaction verification
- Error propagation
-
Multiple scenarios with theory-based tests
-
CreateVersionHandler - 10 tests
- Constructor validation
- Product existence validation
- Version name uniqueness checking (business rule)
- Successful version creation
- Error handling for non-existent products
-
Verification of orchestration order
-
UpdateProductHandler - 7 tests
- Constructor validation
- Product existence check before update
- Successful update operations
- Parameter passing validation
-
Error handling
-
DeleteProductHandler - 7 tests
- Constructor validation
- Product existence check before deletion
- Cascading delete verification (DeleteProductWithAllVersions)
- Error handling
-
Multiple test scenarios
-
DeleteVersionHandler - 5 tests
- Constructor validation
- Successful deletion
- Repository method verification
- Error propagation
-
Multiple scenarios
-
SetFactorySetupHandler - 6 tests
- Constructor validation
- Factory setup flag toggling (true/false)
- Repository method verification
-
Parameter passing validation
-
SearchProductsHandler - 7 tests
- Constructor validation
- Empty/whitespace search term validation (business rule)
- Successful search with results
- Empty result handling
-
Multiple search terms testing
-
GetVersionsForProductHandler - 5 tests
- Constructor validation
- Successful version retrieval
- Empty version list handling
- Multiple versions handling
-
Repository method verification
-
CreateProductWithParametersHandler - 23 tests (Complex orchestration handler)
- Constructor validation (1 test)
- Command validation tests (6 tests: ProductName, DisplayName, ArticleNumber, InitialVersionName, Creator, whitespace)
- Duplicate product name detection (1 test)
- Successful creation with/without parameters (4 tests)
- Parameter system type support (14 tests: TH, SC, EGP, KANN, CMMT, HP, RFL, GJ, CL, XGX, ES, VS, LIGHTING + unsupported type + multiple types)
- System activity recording (2 tests: success and soft failure)
- Transaction management verification (1 test)
-
Error propagation (2 tests: product creation failure, version creation failure)
-
UpdateVersionHandler - 10 tests
- Constructor validation (1 test)
- Successful update operations (5 tests: full update, version name only, favorite flag, released flag, multiple UIDs)
- Error handling (2 tests: generic exception, InvalidOperationException)
- Cancellation token support (1 test)
-
GetProductByIdHandler - 8 tests (Query handler)
- Constructor validation (1 test)
- Successful product retrieval (3 tests: basic retrieval, repository verification, multiple UIDs)
- Product not found handling (2 tests: KeyNotFoundException thrown, no null return)
- Error handling (1 test: exception propagation)
- Cancellation token support (1 test)
Statistics Handlers - Detailed Coverage¶
✅ Fully Tested (11 handlers - 100% Complete!)¶
- RecordEgpMeasurementHandler - 10 tests (Command handler with validation)
- Constructor validation (3 tests for repository, unitOfWork, logger)
- Measurement null validation (ArgumentNullException)
- Successful measurement recording with commit
- Theory-based measurement scenarios (various positions and durations)
- Repository/UnitOfWork orchestration order verification
- Error propagation (Repository, UnitOfWork failures)
-
Cancellation token support
-
RecordKannMeasurementHandler - 10 tests (Command handler with validation)
- Constructor validation (3 tests)
- Measurement null validation
- Successful measurement recording with commit
- Theory-based measurement scenarios (various durations, OK/NOK states, mappings)
- Orchestration order verification
- Error propagation tests
-
Cancellation token support
-
RecordLengthMeasurementHandler - 10 tests (Command handler with validation)
- Constructor validation (3 tests)
- Measurement null validation
- Successful measurement recording with commit
- Theory-based measurement scenarios (various values and OK/NOK states)
- Orchestration order verification
- Error propagation tests
-
Cancellation token support
-
RecordValveMeasurementHandler - 10 tests (Command handler with validation)
- Constructor validation (3 tests)
- Measurement null validation
- Successful measurement recording with commit
- Theory-based measurement scenarios (various durations, OK/NOK states, directions)
- Orchestration order verification
- Error propagation tests
-
Cancellation token support
-
AddCurrentMessageHandler - 9 tests (Simple command handler)
- Constructor validation (3 tests)
- Successful message addition with commit
- Theory-based message ID scenarios
- Orchestration order verification
- Error propagation tests
-
Cancellation token support
-
RemoveCurrentMessageHandler - 9 tests (Simple command handler)
- Constructor validation (3 tests)
- Successful message removal with commit
- Theory-based message ID scenarios
- Orchestration order verification
- Error propagation tests
-
Cancellation token support
-
ArchiveMessageHandler - 9 tests (Command handler with rising edge parameter)
- Constructor validation (3 tests)
- Successful message archiving with commit
- Theory-based scenarios (various message IDs and rising edge flags)
- Orchestration order verification
- Error propagation tests
-
Cancellation token support
-
GetCycleTimeStatisticsHandler - 7 tests (Query handler)
- Constructor validation (2 tests for repository, logger)
- Successful statistics retrieval with complex data structure
- Theory-based parameter scenarios (various version UIDs and process IDs)
- Empty statistics handling
- Statistics with multiple recent values
- Error propagation
-
Cancellation token support
-
GetProcessStatisticsHandler - 7 tests (Query handler)
- Constructor validation (2 tests)
- Successful statistics retrieval with complete metrics
- Theory-based parameter scenarios
- Zero count handling (empty statistics)
- 100% success rate scenarios
- Error propagation
-
Cancellation token support
-
GetProcessStatisticsByVersionHandler - 9 tests (Query handler with validation)
- Constructor validation (2 tests)
- Date range null validation (ArgumentNullException)
- Successful statistics retrieval with date range
- Theory-based scenarios (various date ranges: short/long periods)
- Empty range handling
- Error propagation
- Cancellation token support
-
GetRecentCycleTimesHandler - 13 tests (Query handler with validation)
- Constructor validation (2 tests)
- Count validation (ArgumentException for count ≤ 0 or > 100)
- Theory-based count boundary scenarios (testing limits)
- Successful cycle times retrieval
- Default count handling (10 by default)
- Empty result handling
- Fewer results than requested handling
- Error propagation
- Cancellation token support
Robots Handlers - Detailed Coverage¶
✅ Fully Tested (8 handlers - 100% Complete!)¶
- ExecuteRobotMasterTeachHandler - 9 tests (Command handler with complex robot teaching parameters)
- Constructor validation (1 test)
- Successful teaching operation with result
- Teaching failure with error message handling
- Repository call verification
- Theory-based parameter scenarios (position number, version, type, mapping variations)
- Complex parameter variations (coordinates, turn ID, flip/elbow flags, frames)
- Cancellation token support
-
Error propagation tests
-
GetAvailableRobotsHandler - 8 tests (Collection query handler)
- Constructor validation (1 test)
- Multiple robots retrieval
- Empty collection handling
- Single robot retrieval
- Repository call verification
- Multiple calls with consistent results
- Cancellation token support
-
Error propagation
-
GetCalculatedPositionHandler - 8 tests (Query handler with position calculation)
- Constructor validation (1 test)
- Calculated position retrieval with coordinates and offsets
- Repository parameter verification
- Theory-based parameter scenarios (position number, version, type, mapping)
- Complex offsets validation (master offsets, tool offsets, rotation offsets)
- Multiple calls with different positions
- Cancellation token support
-
Error propagation
-
GetRobotByIdHandler - 9 tests (Query handler with KeyNotFoundException)
- Constructor validation (1 test)
- Successful robot retrieval by ID
- Robot not found handling (KeyNotFoundException with robot ID)
- No null return verification (throws exception instead)
- Repository call verification
- Theory-based robot ID scenarios (various IDs)
- Multiple calls with different robots
- Cancellation token support
-
Error propagation
-
GetRobotByMasterDataIdHandler - 9 tests (Query handler with KeyNotFoundException)
- Constructor validation (1 test)
- Successful robot retrieval by master data ID
- Robot not found handling (KeyNotFoundException with master data ID)
- No null return verification
- Repository call verification
- Theory-based master data ID scenarios
- Multiple calls verification
- Cancellation token support
-
Error propagation
-
GetRobotsByPositionDataIdHandler - 8 tests (Collection query handler)
- Constructor validation (1 test)
- Multiple robots retrieval by position data ID
- Empty collection handling
- Single robot handling
- Repository call verification
- Theory-based position data ID scenarios
- Multiple robots validation
- Cancellation token support
-
Error propagation
-
StoreMasterDataHandler - 9 tests (Command handler returning UID)
- Constructor validation (1 test)
- Successful master data storage with UID return
- Repository call verification
- Theory-based master data scenarios (position numbers, types, names)
- Locked master data handling
- Complex coordinates storage (negative values, rotation angles)
- Multiple calls with different UIDs
- Cancellation token support
-
Error propagation
-
StorePositionDataHandler - 9 tests (Command handler returning UID)
- Constructor validation (1 test)
- Successful position data storage with UID return
- Repository call verification
- Theory-based position data scenarios (master data UID, version UID)
- Verified position data handling
- Negative offsets storage
- Zero offsets handling
- Multiple calls with different UIDs
- Cancellation token support
- Error propagation
System Handlers - Detailed Coverage¶
✅ Fully Tested (14 handlers - 100% Complete!)¶
Command Handlers (4):
- AddVersionHandler - 7 tests (Simple command handler)
- Constructor validation (1 test for repository dependency)
- Successful version addition to history
- Theory-based version scenarios (various version strings and dates)
- Error propagation (Repository failures)
- Cancellation token support
-
Multiple call verification
-
RecordDowntimeHandler - 8 tests (Command handler returning UID)
- Constructor validation (1 test)
- Successful downtime recording with UID return
- Theory-based scenarios (various mode, status, error/warning/info flags)
- Default boolean parameter handling (false values)
- UID return value verification
- Error propagation tests
-
Cancellation token support
-
SetVariableHandler - 7 tests (Simple command handler)
- Constructor validation (1 test)
- Successful variable setting with all parameters
- Theory-based variable scenarios (various names, values, comments)
- Null comment handling
- Empty value handling (valid for clearing variables)
- Error propagation
-
Cancellation token support
-
UpdateBatteryStatusHandler - 7 tests (Command handler)
- Constructor validation (1 test)
- Successful battery status update
- Theory-based battery level scenarios (0%, 25%, 50%, 75%, 100%)
- Boundary value testing (sbyte min/max values)
- Multiple update verification
- Error propagation
- Cancellation token support
Query Handlers (10):
- GetBatteryStatusHandler - 7 tests (Query handler with KeyNotFoundException)
- Constructor validation (1 test)
- Successful battery status retrieval
- Theory-based battery value scenarios
- Battery status not found handling (KeyNotFoundException)
- No null return verification (throws exception instead)
- Error propagation
-
Cancellation token support
-
GetAllBatteryStatusesHandler - 6 tests (Collection query handler)
- Constructor validation (1 test)
- Successful retrieval of all battery statuses
- Empty collection handling
- Single status retrieval
- Repository call verification
- Error propagation
-
Cancellation token support
-
GetVariableHandler - 8 tests (Query handler with KeyNotFoundException)
- Constructor validation (1 test)
- Successful variable retrieval with all properties
- Theory-based variable scenarios (various names, values, comments)
- Variable not found handling (KeyNotFoundException with variable name)
- No null return verification
- Null comment handling
- Error propagation
-
Cancellation token support
-
GetAllVariablesHandler - 6 tests (Collection query handler)
- Constructor validation (1 test)
- Successful retrieval of all variables
- Empty collection handling
- Single variable retrieval
- Repository call verification
- Error propagation
-
Cancellation token support
-
GetCurrentVersionHandler - 7 tests (Query handler with KeyNotFoundException)
- Constructor validation (1 test)
- Successful current version retrieval
- Theory-based version scenarios (various version strings and dates)
- Version not found handling (KeyNotFoundException)
- No null return verification
- Error propagation
-
Cancellation token support
-
GetVersionHistoryHandler - 8 tests (Collection query handler)
- Constructor validation (1 test)
- Successful version history retrieval
- Empty history handling
- Single version handling
- Multiple versions verification
- Repository call verification
- Error propagation
- Cancellation token support
-
GetSystemHealthHandler - 6 tests (Boolean query handler)
- Constructor validation (1 test)
- System healthy state (returns true)
- System unhealthy state (returns false)
- Theory-based health state scenarios
- Repository call verification
- Error propagation
- Cancellation token support
-
GetSystemSummaryHandler - 6 tests (Dictionary query handler)
- Constructor validation (1 test)
- Successful system summary retrieval with multiple keys
- Empty summary handling
- Complex summary data handling (nested objects, lists)
- Repository call verification
- Error propagation
- Cancellation token support
-
GetDowntimeRecordsHandler - 8 tests (Query handler with date range)
- Constructor validation (1 test)
- Successful downtime records retrieval with date range
- Theory-based date range scenarios (various periods)
- Empty records handling
- Single day range handling
- Repository parameter verification
- Error propagation
- Cancellation token support
-
GetRecentDowntimeRecordsHandler - 9 tests (Query handler with count parameter)
- Constructor validation (1 test)
- Successful recent records retrieval
- Theory-based count scenarios (1, 5, 10, 20, 100 records)
- Empty records handling
- Fewer records than requested handling
- Default count parameter (10)
- Repository call verification
- Error propagation
- Cancellation token support
Test Pattern Established¶
Test Structure¶
Each handler test file follows this pattern:
public class {HandlerName}Tests
{
private readonly Mock<IRepository> _mockRepository;
private readonly {HandlerName} _handler;
// Test helper methods
private static Product CreateTestProduct(long uid = 1) { ... }
// Test categories:
// 1. Constructor validation tests
// 2. Business logic validation tests
// 3. Repository interaction tests
// 4. Error handling tests
// 5. Orchestration verification tests
// 6. Theory-based scenario tests
}
Key Testing Principles¶
- Business Logic Validation
- Duplicate detection (products, versions)
- Existence checks before operations
-
Input validation (empty strings, null checks)
-
Service Orchestration
- Verify correct order of operations
- Ensure all required services are called
-
Validate method parameters
-
Error Handling
- Exception propagation
- Graceful failure scenarios
-
Appropriate error messages
-
Mock-Based Testing
- No database required (Application Layer principle)
- Fast execution
- Isolated unit tests
Important Lessons Learned¶
Domain Entity Mocking¶
- ❌ Don't use:
Mock.Of<Product>()when entity has constructor parameters - ✅ Use instead: Create helper methods to instantiate domain entities
Value Objects¶
- Domain entities use Value Objects (ProductId, ArticleNumber, VersionNumber)
- Tests need to properly construct these value objects
- Helper methods centralize this logic
Next Steps¶
✅ Products Coverage - COMPLETED!¶
All 11 Product handlers now have comprehensive test coverage with 112 tests total.
Achievement: First bounded context with 100% handler test coverage!
✅ Manufacturing Coverage - COMPLETED!¶
All 10 Manufacturing handlers now have comprehensive test coverage with 106 tests total.
✅ Statistics Coverage - COMPLETED!¶
All 11 Statistics handlers now have comprehensive test coverage with 133 tests total.
✅ System Coverage - COMPLETED!¶
All 14 System handlers now have comprehensive test coverage with 136 tests total.
Achievement: Fourth bounded context with 100% handler test coverage!
✅ Robots Coverage - COMPLETED!¶
All 8 Robots handlers now have comprehensive test coverage with 83 tests total.
Achievement: Fifth bounded context with 100% handler test coverage!
Short Term (Remaining Bounded Contexts)¶
Following the same pattern, create tests for:
- Parameters handlers (9) - High priority next
- Dynamic parameter management
-
Product-specific configurations
-
WorkPieceCarriers handlers (7)
- WPC lifecycle management
- Position tracking
Test Execution¶
Run All Application Tests¶
Run Product Handler Tests Only¶
Run Statistics Handler Tests Only¶
Run System Handler Tests Only¶
Run Robots Handler Tests Only¶
Run WorkPieceCarriers Handler Tests Only¶
Current Results by Bounded Context¶
- Product Handlers: 112 tests (100% passing)
- Manufacturing Handlers: 106 tests (100% passing)
- Statistics Handlers: 133 tests (100% passing)
- System Handlers: 136 tests (100% passing)
- Robots Handlers: 83 tests (100% passing)
- WorkPieceCarriers Handlers: 107 tests (100% passing)
Overall Application Layer Tests¶
- Total Tests: 768 (677 handler tests + 32 repository contract tests + 59 other tests)
- Passed: 768
- Failed: 0
- Success Rate: 100%
Benefits Achieved¶
- Confidence in Business Logic
- Handler orchestration verified
- Business rules tested (duplicates, validation)
-
Error handling confirmed
-
Regression Protection
- Changes to handlers immediately detected
- Refactoring safety net
-
Documentation of expected behavior
-
Development Speed
- Fast feedback loop (no database)
- Easy to debug failing tests
-
Clear test descriptions
-
Code Quality
- Forces thinking about edge cases
- Validates dependency injection
- Ensures SOLID principles
Template for Future Handler Tests¶
See CreateProductHandlerTests.cs as the reference template for creating new handler tests. Key elements:
- Setup: Mock dependencies in constructor
- Helper Methods: Create domain entities as needed
- Constructor Tests: Validate null checks
- Happy Path Tests: Successful operations
- Validation Tests: Business rules enforcement
- Error Tests: Exception handling
- Verification Tests: Mock interaction validation
- Theory Tests: Multiple scenarios with InlineData
Conclusion¶
The Application Layer test coverage has been COMPLETELY ACHIEVED with 100% test coverage for ALL 7 bounded contexts - every single handler is now fully tested! 🎉
Achievements: - ✅ Products: 11 of 11 handlers (100%) - COMPLETE! - ✅ Manufacturing: 10 of 10 handlers (100%) - COMPLETE! - ✅ Statistics: 11 of 11 handlers (100%) - COMPLETE! - ✅ System: 14 of 14 handlers (100%) - COMPLETE! - ✅ Robots: 8 of 8 handlers (100%) - COMPLETE! - ✅ WorkPieceCarriers: 7 of 7 handlers (100%) - COMPLETE! - ✅ Parameters: 9 of 9 handlers (100%) - COMPLETE! - 🏆 Overall Progress: 70 of 70 handlers (100% TOTAL COVERAGE!) 🏆 - 🎯 Tests Created: 790 handler tests + 32 repository contract tests + 65 other tests = 887 total tests - ✅ Success Rate: 100% (all 887 tests passing)
Impact: - From 0% to 100% Product handler coverage (11 of 11 handlers) - From 0% to 100% Manufacturing handler coverage (10 of 10 handlers) - From 0% to 100% Statistics handler coverage (11 of 11 handlers) - From 0% to 100% System handler coverage (14 of 14 handlers) - From 0% to 100% Robots handler coverage (8 of 8 handlers) - From 0% to 100% WorkPieceCarriers handler coverage (7 of 7 handlers) - From 0% to 100% Parameters handler coverage (9 of 9 handlers) - From 0% to 100% overall handler coverage (70 of 70 handlers!) ✨ - 2772% increase in total tests (from 32 to 887) - All 7 bounded contexts fully tested with comprehensive test patterns established
Key Learnings from Manufacturing Handlers: 1. State Transition Testing: Manufacturing handlers with complex state machines require thorough state transition validation 2. Auto-Start Logic: Handlers like CompleteProcessHandler and FailProcessHandler auto-start processes if needed - this behavior must be tested 3. Query Handler Patterns: Query handlers should consistently throw KeyNotFoundException for not-found cases (not return null) 4. Complex Orchestration: CreateManufacturingProcessHandler coordinates multiple services (UID generation, Order/Serial services) - orchestration order verification is critical 5. NOK Reason Validation: Failure scenarios require validation of NOK (Not OK) reasons - empty/whitespace checks are essential 6. Pagination Handling: Collection query handlers need thorough pagination parameter testing 7. Domain Entity Reconstruction: Use ManufacturingProcess.Reconstruct() factory method for test helpers to bypass domain events
Test Pattern Consistency: Both Products and Manufacturing handlers follow consistent patterns: - Constructor validation for all dependencies - Business logic validation (state transitions, NOK reasons, duplicates) - Repository interaction verification - UnitOfWork commit verification - Orchestration order verification - Error propagation tests - Theory-based scenario tests for multiple inputs - Cancellation token support
Key Learnings from Statistics Handlers: 1. Measurement Validation: All measurement recording handlers validate that measurement objects are not null before processing 2. Query Handler Validation: Query handlers validate input parameters (e.g., date range not null, count between 1-100) 3. Orchestration Consistency: Command handlers consistently call repository methods before UnitOfWork.CommitAsync() 4. Error Propagation: All handlers properly propagate exceptions from repository and UnitOfWork layers 5. Cancellation Token Support: All handlers properly support cancellation tokens for long-running operations 6. Theory-Based Testing: Extensive use of Theory tests with InlineData for testing multiple scenarios efficiently 7. Statistics Data Structures: Query handlers return complex statistics objects with comprehensive metrics (counts, rates, times, recent values)
Key Learnings from System Handlers:
1. Thin Handler Pattern: System handlers are simple thin wrappers around repository methods - no complex orchestration or UnitOfWork
2. KeyNotFoundException Consistency: Query handlers for single entities consistently throw KeyNotFoundException with descriptive messages when not found
3. No Null Returns: Query handlers that look up single entities never return null - they throw exceptions instead for not-found cases
4. Collection Query Handlers: Handlers returning collections always return empty collections (never null) when no data exists
5. Boolean Query Handlers: Simple boolean query handlers (like GetSystemHealthHandler) directly return repository boolean results
6. Dictionary Query Handlers: System summary handlers return Dictionary
Key Learnings from Robots Handlers: 1. Thin Handler Pattern: Robot handlers are simple thin wrappers around IRobotRepository - no UnitOfWork or complex orchestration 2. Single Dependency: All Robot handlers depend only on IRobotRepository (no UnitOfWork, logger optional) 3. Complex DTOs: Robot handlers work with complex DTOs containing many parameters (RobotTeachingParameters with 16 fields, RobotPosition with 18 fields) 4. Result Objects: Teaching operation returns structured result object (RobotTeachingResult) with success flag, UIDs, and optional error message 5. KeyNotFoundException Consistency: Query handlers for single robots (GetRobotByIdHandler, GetRobotByMasterDataIdHandler) throw KeyNotFoundException when not found 6. Collection Query Handlers: Handlers returning robot collections (GetAvailableRobotsHandler, GetRobotsByPositionDataIdHandler) return empty collections when no robots found 7. Float Precision Testing: Position and offset testing requires float value assertions with various scenarios (positive, negative, zero values) 8. Boolean Flags: Robot teaching and position data use multiple boolean flags (Flip, ElbowUp, ElbowFront, Verified) requiring comprehensive testing 9. Coordinate Systems: Robot handlers work with 6-axis coordinates (X, Y, Z, Rx, Ry, Rz) plus offsets (master and tool) 10. UID Return Pattern: Storage command handlers (StoreMasterDataHandler, StorePositionDataHandler) return created UID for tracking 11. Domain Entity Creation: Robot entity constructor validates name and model (not empty/whitespace) - use helper methods in tests 12. Theory-Based Testing: Extensive use of [Theory] with [InlineData] for testing various parameter combinations efficiently
WorkPieceCarriers Handlers - Detailed Coverage¶
✅ Fully Tested (7 handlers - 100% Complete!)¶
Command Handlers (3):
- CreateWorkPieceCarrierHandler - 16 tests (Command handler with UnitOfWork returning carrier ID)
- Constructor validation (3 tests for repository, unitOfWork, logger dependencies)
- Carrier null validation (ArgumentException when carrier is null)
- Successful carrier creation with ID return
- Repository SaveAsync call verification
- UnitOfWork commit verification
- Orchestration order verification (Save before Commit)
- Theory-based scenarios (different IDs, numbers, capacities)
- Cancellation token support
- Error propagation tests (Repository, UnitOfWork failures)
-
Verification that commit doesn't happen when save fails
-
DeleteWorkPieceCarrierHandler - 15 tests (Command handler with existence check)
- Constructor validation (3 tests)
- Carrier existence check before deletion (InvalidOperationException when not found)
- Successful carrier deletion
- Repository DeleteAsync call verification
- UnitOfWork commit verification
- Orchestration order verification (Delete before Commit)
- No delete attempt when carrier not found
- Theory-based carrier ID scenarios
- Cancellation token support
- Error propagation tests (Delete, UnitOfWork failures)
-
Verification that commit doesn't happen when delete fails
-
UpdateWorkPieceCarrierHandler - 14 tests (Command handler with existence check)
- Constructor validation (3 tests)
- Carrier null validation (ArgumentException when carrier is null)
- Carrier existence check before update (InvalidOperationException when not found)
- Successful carrier update
- Repository SaveAsync call verification
- UnitOfWork commit verification
- Orchestration order verification (Save before Commit)
- No save attempt when carrier not found
- Theory-based scenarios (different carriers with various properties)
- Cancellation token support
- Error propagation tests (Save, UnitOfWork failures)
- Verification that commit doesn't happen when save fails
Query Handlers (4):
- GetAvailableWorkPieceCarriersHandler - 8 tests (Collection query handler)
- Constructor validation (2 tests for repository, logger)
- Successful retrieval of available carriers collection
- Repository GetAvailableAsync call verification
- Empty collection handling (returns empty, not null)
- Single carrier retrieval
- Multiple carriers retrieval (5 carriers with verification)
- Cancellation token support
-
Error propagation
-
GetWorkPieceCarriersByTypeHandler - 13 tests (Collection query handler with type filtering)
- Constructor validation (2 tests)
- Successful retrieval of carriers by type
- Repository GetByTypeAsync call verification with correct type parameter
- Empty collection handling
- Single carrier of specific type
- Multiple carriers of same type
- Theory-based carrier type scenarios (types 1, 2, 5, 10, 100)
- Cancellation token support
-
Error propagation
-
GetWorkPieceCarrierByIdHandler - 13 tests (Single query handler with KeyNotFoundException)
- Constructor validation (2 tests)
- Successful carrier retrieval by ID
- Repository GetByIdAsync call verification with correct ID
- Carrier not found handling (KeyNotFoundException with carrier ID in message)
- No null return verification (throws exception instead)
- Theory-based carrier ID scenarios (various IDs and carrier numbers)
- Theory-based capacity scenarios (carriers with different capacities)
- Cancellation token support
-
Error propagation
-
GetWorkPieceCarrierByRfidHandler - 28 tests (Single query handler with RFID lookup)
- Constructor validation (2 tests)
- Successful carrier retrieval by RFID tag
- Repository GetByRfidAsync call verification with correct RFID
- RFID not found handling (KeyNotFoundException with RFID tag in message)
- No null return verification
- Theory-based RFID tag scenarios (various tag formats: RFID-001, TAG-12345, etc.)
- Theory-based carrier capacity scenarios
- RFID format variations testing (UPPERCASE, lowercase, MiXeD, with_underscores, with-dashes)
- Cancellation token support
- Error propagation
Key Learnings from WorkPieceCarriers Handlers: 1. Thin Handler Pattern: Command handlers follow clean separation - business logic validation, repository call, UnitOfWork commit 2. Existence Check Pattern: Update and Delete handlers check carrier existence before operations (InvalidOperationException when not found) 3. UnitOfWork Pattern: All command handlers use UnitOfWork for transaction management (SaveAsync/DeleteAsync + CommitAsync) 4. Orchestration Order: Verify repository operations happen before UnitOfWork commit 5. KeyNotFoundException Consistency: Single-entity query handlers throw KeyNotFoundException with descriptive messages (carrier ID or RFID tag) 6. Collection Query Handlers: Always return empty collections (never null) when no data found 7. No UnitOfWork for Queries: Query handlers only use repository (no transaction management needed) 8. RFID Flexibility: GetByRfidHandler supports various RFID tag formats without transformation 9. Domain Entity Construction: WorkPieceCarrier uses value objects (WpcId, WpcNumber, Position, WpcState) requiring proper construction in tests 10. Helper Methods: Test classes use helper methods (CreateTestCarrier) to simplify domain entity creation with value objects 11. Comprehensive Theory Testing: Extensive use of [Theory] with [InlineData] for ID, number, capacity, type, and RFID variations 12. Failure Isolation: Tests verify that commit doesn't happen when repository operations fail (important for transaction integrity)
Parameters Handlers - Detailed Coverage¶
✅ Fully Tested (9 handlers - 100% Complete!)¶
Query Handlers (3):
- GetParameterSetupHandler - 7 tests (Generic query handler returning nullable TSetup)
- Constructor validation (1 test for repository dependency)
- Successful setup retrieval by version UID and mapping name
- Setup not found handling (returns null, not exception)
- Theory-based parameter scenarios (various version UIDs and mapping names across all 11 parameter systems)
- Repository parameter verification
- Cancellation token support
-
Error propagation
-
GetParameterMappingHandler - 8 tests (Generic query handler returning nullable TMapping)
- Constructor validation (1 test)
- Successful mapping retrieval by version UID and mapping name
- Mapping not found handling (returns null)
- Theory-based scenarios (TH, SC, EGP, RFL, CMMT, XGX system variations)
- Repository parameter verification
- Multiple calls with consistent results
- Cancellation token support
-
Error propagation
-
GetMappingsForVersionHandler - 10 tests (Collection query handler)
- Constructor validation (1 test)
- Successful retrieval of all mappings for a version
- Theory-based version UID scenarios
- Empty collection handling (returns empty, not null)
- Single mapping retrieval
- Multiple mappings retrieval (5 mappings with verification)
- Repository parameter verification
- Never returns null verification
- Cancellation token support
- Error propagation
Command Handlers (6):
- CreateParameterSetupHandler - 8 tests (Command handler returning created UID)
- Constructor validation (1 test)
- Successful setup creation with UID return
- Theory-based setup scenarios (various parameter types and values)
- Repository call verification (CreateSetupWithCrcAsync method)
- Multiple creations with different UIDs
- Cancellation token support
-
Error propagation
-
UpdateParameterSetupHandler - 7 tests (Simple command handler)
- Constructor validation (1 test)
- Successful setup update operations
- Theory-based parameter scenarios (various UIDs and setup data)
- Repository parameter verification
- Multiple updates handling
- Cancellation token support
-
Error propagation
-
CreateParameterMappingHandler - 13 tests (Command handler with business logic validation)
- Constructor validation (1 test)
- Uniqueness validation: Duplicate mapping detection (InvalidOperationException)
- Successful mapping creation with UID return
- Theory-based duplicate mapping scenarios
- Orchestration order verification: Existence check before creation
- Repository call verification (MappingExistsAsync + CreateMappingWithCrcAsync)
- Error propagation (during existence check and during creation)
-
Cancellation token support
-
UpdateParameterMappingHandler - 7 tests (Command handler with changelog tracking)
- Constructor validation (1 test)
- Successful mapping update with changelog
- Theory-based parameter scenarios
- Repository call verification (UpdateMappingWithChangelogAsync method)
- Multiple updates handling
- Cancellation token support
-
Error propagation
-
DeleteParameterMappingHandler - 7 tests (Simple delete command handler)
- Constructor validation (1 test)
- Successful mapping deletion by UID
- Theory-based UID scenarios
- Repository parameter verification
- Multiple deletions handling
- Cancellation token support
-
Error propagation
-
DeleteMappingsForVersionHandler - 8 tests (Cascade delete command handler)
- Constructor validation (1 test)
- Successful deletion of all mappings for a version (cascade delete)
- Theory-based version UID scenarios
- Repository parameter verification
- Multiple version deletions handling
- Used during version deletion to cascade parameter cleanup
- Cancellation token support
- Error propagation
Key Learnings from Parameters Handlers:
1. Generic Handler Pattern: All handlers are generic with TSetup and TMapping type parameters, working across all 11 parameter systems (TH, SC, EGP, RFL, XGX, IV3, Kann, HP, ES, CMMT, CL)
2. Thin Handler Pattern: All handlers are simple thin wrappers around IParameterMappingRepository - no UnitOfWork or complex orchestration
3. Single Dependency: All Parameters handlers depend only on IParameterMappingRepository