Skip to content

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!)

  1. CreateManufacturingProcessHandler - 18 tests (Complex orchestration handler)
  2. Constructor validation (6 tests for all dependencies)
  3. Command validation (9 tests: OrderNumber, SerialNumber, WpcId validation)
  4. Successful process creation with UID generation
  5. Service orchestration (UID generation, Order/Serial services)
  6. Repository and UnitOfWork interaction verification
  7. Orchestration order verification
  8. Error propagation (Repository, OrderSerialService, UnitOfWork failures)
  9. Theory-based scenario tests

  10. UpdateProcessStateHandler - 14 tests (State transition handler)

  11. Constructor validation (3 tests)
  12. Process not found handling
  13. State transitions (NotStarted -> InProgress, InProgress -> Completed, InProgress -> Failed, NotStarted/InProgress -> Cancelled)
  14. NOK reason validation for Failed state
  15. Default reason for Cancelled state without reason
  16. Already in target state handling
  17. Orchestration order verification
  18. Error propagation tests

  19. CompleteProcessHandler - 10 tests

  20. Constructor validation (3 tests)
  21. Process not found handling
  22. Auto-start process if NotStarted
  23. Complete InProgress process
  24. Repository and UnitOfWork verification
  25. Orchestration order verification
  26. Error handling (Repository, UnitOfWork failures)
  27. Multiple process ID scenarios

  28. FailProcessHandler - 11 tests

  29. Constructor validation (3 tests)
  30. NOK reason validation (empty, whitespace, null)
  31. Process not found handling
  32. Auto-start process if NotStarted then fail
  33. Fail InProgress process
  34. Repository and UnitOfWork verification
  35. Orchestration order verification
  36. Error handling (Repository, UnitOfWork failures)
  37. Theory-based NOK reason scenarios

  38. GetActiveProcessesHandler - 8 tests (Query handler)

  39. Constructor validation (2 tests)
  40. Default pagination handling
  41. Custom pagination parameter passing
  42. Empty collection handling
  43. Multiple processes retrieval
  44. Theory-based pagination scenarios
  45. Cancellation token support
  46. Error propagation

  47. GetProcessesByWpcIdHandler - 8 tests (Query handler)

  48. Constructor validation (2 tests)
  49. Process retrieval by WPC ID
  50. Repository parameter verification
  51. Empty collection handling
  52. Multiple processes for single WPC
  53. Theory-based WPC ID scenarios
  54. Cancellation token support
  55. Error propagation

  56. GetProcessByIdHandler - 9 tests (Query handler)

  57. Constructor validation (2 tests)
  58. Successful process retrieval
  59. Process not found handling (KeyNotFoundException)
  60. No null return verification
  61. Repository call verification
  62. Theory-based process ID scenarios
  63. Cancellation token support
  64. Error propagation
  65. Multiple calls verification

  66. GetProcessByOrderNumberHandler - 9 tests (Query handler)

  67. Constructor validation (2 tests)
  68. Successful process retrieval by order number
  69. Process not found handling (KeyNotFoundException)
  70. No null return verification
  71. Repository call verification
  72. Theory-based order number scenarios
  73. Cancellation token support
  74. Error propagation
  75. Multiple calls verification

  76. UpdateManufacturingProcessHandler - 9 tests

  77. Constructor validation (3 tests)
  78. Process not found handling
  79. Successful process update
  80. Repository and UnitOfWork verification
  81. Orchestration order verification
  82. Process existence check before update
  83. Theory-based process ID scenarios
  84. Error handling (Repository, UnitOfWork failures)

  85. 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!)

  1. CreateProductHandler - 11 tests
  2. Constructor validation
  3. Successful creation with valid request
  4. Duplicate name detection (business rule)
  5. Repository interaction verification
  6. Error propagation
  7. Multiple scenarios with theory-based tests

  8. CreateVersionHandler - 10 tests

  9. Constructor validation
  10. Product existence validation
  11. Version name uniqueness checking (business rule)
  12. Successful version creation
  13. Error handling for non-existent products
  14. Verification of orchestration order

  15. UpdateProductHandler - 7 tests

  16. Constructor validation
  17. Product existence check before update
  18. Successful update operations
  19. Parameter passing validation
  20. Error handling

  21. DeleteProductHandler - 7 tests

  22. Constructor validation
  23. Product existence check before deletion
  24. Cascading delete verification (DeleteProductWithAllVersions)
  25. Error handling
  26. Multiple test scenarios

  27. DeleteVersionHandler - 5 tests

  28. Constructor validation
  29. Successful deletion
  30. Repository method verification
  31. Error propagation
  32. Multiple scenarios

  33. SetFactorySetupHandler - 6 tests

  34. Constructor validation
  35. Factory setup flag toggling (true/false)
  36. Repository method verification
  37. Parameter passing validation

  38. SearchProductsHandler - 7 tests

  39. Constructor validation
  40. Empty/whitespace search term validation (business rule)
  41. Successful search with results
  42. Empty result handling
  43. Multiple search terms testing

  44. GetVersionsForProductHandler - 5 tests

  45. Constructor validation
  46. Successful version retrieval
  47. Empty version list handling
  48. Multiple versions handling
  49. Repository method verification

  50. CreateProductWithParametersHandler - 23 tests (Complex orchestration handler)

  51. Constructor validation (1 test)
  52. Command validation tests (6 tests: ProductName, DisplayName, ArticleNumber, InitialVersionName, Creator, whitespace)
  53. Duplicate product name detection (1 test)
  54. Successful creation with/without parameters (4 tests)
  55. Parameter system type support (14 tests: TH, SC, EGP, KANN, CMMT, HP, RFL, GJ, CL, XGX, ES, VS, LIGHTING + unsupported type + multiple types)
  56. System activity recording (2 tests: success and soft failure)
  57. Transaction management verification (1 test)
  58. Error propagation (2 tests: product creation failure, version creation failure)

  59. 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)
  60. 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!)

  1. RecordEgpMeasurementHandler - 10 tests (Command handler with validation)
  2. Constructor validation (3 tests for repository, unitOfWork, logger)
  3. Measurement null validation (ArgumentNullException)
  4. Successful measurement recording with commit
  5. Theory-based measurement scenarios (various positions and durations)
  6. Repository/UnitOfWork orchestration order verification
  7. Error propagation (Repository, UnitOfWork failures)
  8. Cancellation token support

  9. RecordKannMeasurementHandler - 10 tests (Command handler with validation)

  10. Constructor validation (3 tests)
  11. Measurement null validation
  12. Successful measurement recording with commit
  13. Theory-based measurement scenarios (various durations, OK/NOK states, mappings)
  14. Orchestration order verification
  15. Error propagation tests
  16. Cancellation token support

  17. RecordLengthMeasurementHandler - 10 tests (Command handler with validation)

  18. Constructor validation (3 tests)
  19. Measurement null validation
  20. Successful measurement recording with commit
  21. Theory-based measurement scenarios (various values and OK/NOK states)
  22. Orchestration order verification
  23. Error propagation tests
  24. Cancellation token support

  25. RecordValveMeasurementHandler - 10 tests (Command handler with validation)

  26. Constructor validation (3 tests)
  27. Measurement null validation
  28. Successful measurement recording with commit
  29. Theory-based measurement scenarios (various durations, OK/NOK states, directions)
  30. Orchestration order verification
  31. Error propagation tests
  32. Cancellation token support

  33. AddCurrentMessageHandler - 9 tests (Simple command handler)

  34. Constructor validation (3 tests)
  35. Successful message addition with commit
  36. Theory-based message ID scenarios
  37. Orchestration order verification
  38. Error propagation tests
  39. Cancellation token support

  40. RemoveCurrentMessageHandler - 9 tests (Simple command handler)

  41. Constructor validation (3 tests)
  42. Successful message removal with commit
  43. Theory-based message ID scenarios
  44. Orchestration order verification
  45. Error propagation tests
  46. Cancellation token support

  47. ArchiveMessageHandler - 9 tests (Command handler with rising edge parameter)

  48. Constructor validation (3 tests)
  49. Successful message archiving with commit
  50. Theory-based scenarios (various message IDs and rising edge flags)
  51. Orchestration order verification
  52. Error propagation tests
  53. Cancellation token support

  54. GetCycleTimeStatisticsHandler - 7 tests (Query handler)

  55. Constructor validation (2 tests for repository, logger)
  56. Successful statistics retrieval with complex data structure
  57. Theory-based parameter scenarios (various version UIDs and process IDs)
  58. Empty statistics handling
  59. Statistics with multiple recent values
  60. Error propagation
  61. Cancellation token support

  62. GetProcessStatisticsHandler - 7 tests (Query handler)

  63. Constructor validation (2 tests)
  64. Successful statistics retrieval with complete metrics
  65. Theory-based parameter scenarios
  66. Zero count handling (empty statistics)
  67. 100% success rate scenarios
  68. Error propagation
  69. Cancellation token support

  70. 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
  71. 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!)

  1. ExecuteRobotMasterTeachHandler - 9 tests (Command handler with complex robot teaching parameters)
  2. Constructor validation (1 test)
  3. Successful teaching operation with result
  4. Teaching failure with error message handling
  5. Repository call verification
  6. Theory-based parameter scenarios (position number, version, type, mapping variations)
  7. Complex parameter variations (coordinates, turn ID, flip/elbow flags, frames)
  8. Cancellation token support
  9. Error propagation tests

  10. GetAvailableRobotsHandler - 8 tests (Collection query handler)

  11. Constructor validation (1 test)
  12. Multiple robots retrieval
  13. Empty collection handling
  14. Single robot retrieval
  15. Repository call verification
  16. Multiple calls with consistent results
  17. Cancellation token support
  18. Error propagation

  19. GetCalculatedPositionHandler - 8 tests (Query handler with position calculation)

  20. Constructor validation (1 test)
  21. Calculated position retrieval with coordinates and offsets
  22. Repository parameter verification
  23. Theory-based parameter scenarios (position number, version, type, mapping)
  24. Complex offsets validation (master offsets, tool offsets, rotation offsets)
  25. Multiple calls with different positions
  26. Cancellation token support
  27. Error propagation

  28. GetRobotByIdHandler - 9 tests (Query handler with KeyNotFoundException)

  29. Constructor validation (1 test)
  30. Successful robot retrieval by ID
  31. Robot not found handling (KeyNotFoundException with robot ID)
  32. No null return verification (throws exception instead)
  33. Repository call verification
  34. Theory-based robot ID scenarios (various IDs)
  35. Multiple calls with different robots
  36. Cancellation token support
  37. Error propagation

  38. GetRobotByMasterDataIdHandler - 9 tests (Query handler with KeyNotFoundException)

  39. Constructor validation (1 test)
  40. Successful robot retrieval by master data ID
  41. Robot not found handling (KeyNotFoundException with master data ID)
  42. No null return verification
  43. Repository call verification
  44. Theory-based master data ID scenarios
  45. Multiple calls verification
  46. Cancellation token support
  47. Error propagation

  48. GetRobotsByPositionDataIdHandler - 8 tests (Collection query handler)

  49. Constructor validation (1 test)
  50. Multiple robots retrieval by position data ID
  51. Empty collection handling
  52. Single robot handling
  53. Repository call verification
  54. Theory-based position data ID scenarios
  55. Multiple robots validation
  56. Cancellation token support
  57. Error propagation

  58. StoreMasterDataHandler - 9 tests (Command handler returning UID)

  59. Constructor validation (1 test)
  60. Successful master data storage with UID return
  61. Repository call verification
  62. Theory-based master data scenarios (position numbers, types, names)
  63. Locked master data handling
  64. Complex coordinates storage (negative values, rotation angles)
  65. Multiple calls with different UIDs
  66. Cancellation token support
  67. Error propagation

  68. StorePositionDataHandler - 9 tests (Command handler returning UID)

  69. Constructor validation (1 test)
  70. Successful position data storage with UID return
  71. Repository call verification
  72. Theory-based position data scenarios (master data UID, version UID)
  73. Verified position data handling
  74. Negative offsets storage
  75. Zero offsets handling
  76. Multiple calls with different UIDs
  77. Cancellation token support
  78. Error propagation

System Handlers - Detailed Coverage

✅ Fully Tested (14 handlers - 100% Complete!)

Command Handlers (4):

  1. AddVersionHandler - 7 tests (Simple command handler)
  2. Constructor validation (1 test for repository dependency)
  3. Successful version addition to history
  4. Theory-based version scenarios (various version strings and dates)
  5. Error propagation (Repository failures)
  6. Cancellation token support
  7. Multiple call verification

  8. RecordDowntimeHandler - 8 tests (Command handler returning UID)

  9. Constructor validation (1 test)
  10. Successful downtime recording with UID return
  11. Theory-based scenarios (various mode, status, error/warning/info flags)
  12. Default boolean parameter handling (false values)
  13. UID return value verification
  14. Error propagation tests
  15. Cancellation token support

  16. SetVariableHandler - 7 tests (Simple command handler)

  17. Constructor validation (1 test)
  18. Successful variable setting with all parameters
  19. Theory-based variable scenarios (various names, values, comments)
  20. Null comment handling
  21. Empty value handling (valid for clearing variables)
  22. Error propagation
  23. Cancellation token support

  24. UpdateBatteryStatusHandler - 7 tests (Command handler)

  25. Constructor validation (1 test)
  26. Successful battery status update
  27. Theory-based battery level scenarios (0%, 25%, 50%, 75%, 100%)
  28. Boundary value testing (sbyte min/max values)
  29. Multiple update verification
  30. Error propagation
  31. Cancellation token support

Query Handlers (10):

  1. GetBatteryStatusHandler - 7 tests (Query handler with KeyNotFoundException)
  2. Constructor validation (1 test)
  3. Successful battery status retrieval
  4. Theory-based battery value scenarios
  5. Battery status not found handling (KeyNotFoundException)
  6. No null return verification (throws exception instead)
  7. Error propagation
  8. Cancellation token support

  9. GetAllBatteryStatusesHandler - 6 tests (Collection query handler)

  10. Constructor validation (1 test)
  11. Successful retrieval of all battery statuses
  12. Empty collection handling
  13. Single status retrieval
  14. Repository call verification
  15. Error propagation
  16. Cancellation token support

  17. GetVariableHandler - 8 tests (Query handler with KeyNotFoundException)

  18. Constructor validation (1 test)
  19. Successful variable retrieval with all properties
  20. Theory-based variable scenarios (various names, values, comments)
  21. Variable not found handling (KeyNotFoundException with variable name)
  22. No null return verification
  23. Null comment handling
  24. Error propagation
  25. Cancellation token support

  26. GetAllVariablesHandler - 6 tests (Collection query handler)

  27. Constructor validation (1 test)
  28. Successful retrieval of all variables
  29. Empty collection handling
  30. Single variable retrieval
  31. Repository call verification
  32. Error propagation
  33. Cancellation token support

  34. GetCurrentVersionHandler - 7 tests (Query handler with KeyNotFoundException)

  35. Constructor validation (1 test)
  36. Successful current version retrieval
  37. Theory-based version scenarios (various version strings and dates)
  38. Version not found handling (KeyNotFoundException)
  39. No null return verification
  40. Error propagation
  41. Cancellation token support

  42. 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
  43. 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
  44. 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
  45. 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
  46. 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

  1. Business Logic Validation
  2. Duplicate detection (products, versions)
  3. Existence checks before operations
  4. Input validation (empty strings, null checks)

  5. Service Orchestration

  6. Verify correct order of operations
  7. Ensure all required services are called
  8. Validate method parameters

  9. Error Handling

  10. Exception propagation
  11. Graceful failure scenarios
  12. Appropriate error messages

  13. Mock-Based Testing

  14. No database required (Application Layer principle)
  15. Fast execution
  16. 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
    private static Product CreateTestProduct(long uid = 1)
    {
        return new Product(
            new ProductId(uid),
            "TestProduct",
            "Test Product Display",
            new ArticleNumber("ART-123")
        );
    }
    

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:

  1. Parameters handlers (9) - High priority next
  2. Dynamic parameter management
  3. Product-specific configurations

  4. WorkPieceCarriers handlers (7)

  5. WPC lifecycle management
  6. Position tracking

Test Execution

Run All Application Tests

dotnet test Essert.MF.Application.Tests --verbosity normal

Run Product Handler Tests Only

dotnet test Essert.MF.Application.Tests --filter "FullyQualifiedName~Products"

Run Statistics Handler Tests Only

dotnet test Essert.MF.Application.Tests --filter "FullyQualifiedName~Statistics"

Run System Handler Tests Only

dotnet test Essert.MF.Application.Tests --filter "FullyQualifiedName~System"

Run Robots Handler Tests Only

dotnet test Essert.MF.Application.Tests --filter "FullyQualifiedName~Robots"

Run WorkPieceCarriers Handler Tests Only

dotnet test Essert.MF.Application.Tests --filter "FullyQualifiedName~WorkPieceCarriers"

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

  1. Confidence in Business Logic
  2. Handler orchestration verified
  3. Business rules tested (duplicates, validation)
  4. Error handling confirmed

  5. Regression Protection

  6. Changes to handlers immediately detected
  7. Refactoring safety net
  8. Documentation of expected behavior

  9. Development Speed

  10. Fast feedback loop (no database)
  11. Easy to debug failing tests
  12. Clear test descriptions

  13. Code Quality

  14. Forces thinking about edge cases
  15. Validates dependency injection
  16. Ensures SOLID principles

Template for Future Handler Tests

See CreateProductHandlerTests.cs as the reference template for creating new handler tests. Key elements:

  1. Setup: Mock dependencies in constructor
  2. Helper Methods: Create domain entities as needed
  3. Constructor Tests: Validate null checks
  4. Happy Path Tests: Successful operations
  5. Validation Tests: Business rules enforcement
  6. Error Tests: Exception handling
  7. Verification Tests: Mock interaction validation
  8. 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 for flexible data structures 7. Date Range Queries: Downtime record handlers use DateTime ranges for filtering historical data 8. Count Parameter Patterns: Recent record handlers use count parameters with sensible defaults (e.g., 10 records) 9. Version Management: Version handlers work with DateOnly for change dates, not DateTime 10. Battery Status Pattern: Battery handlers use sbyte for value/state pairs with boundary value testing 11. Single Dependency: All System handlers depend only on ISystemConfigurationRepository (no UnitOfWork or other dependencies) 12. Parameter Validation: System handlers rely on repository layer for validation - application layer is thin

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):

  1. CreateWorkPieceCarrierHandler - 16 tests (Command handler with UnitOfWork returning carrier ID)
  2. Constructor validation (3 tests for repository, unitOfWork, logger dependencies)
  3. Carrier null validation (ArgumentException when carrier is null)
  4. Successful carrier creation with ID return
  5. Repository SaveAsync call verification
  6. UnitOfWork commit verification
  7. Orchestration order verification (Save before Commit)
  8. Theory-based scenarios (different IDs, numbers, capacities)
  9. Cancellation token support
  10. Error propagation tests (Repository, UnitOfWork failures)
  11. Verification that commit doesn't happen when save fails

  12. DeleteWorkPieceCarrierHandler - 15 tests (Command handler with existence check)

  13. Constructor validation (3 tests)
  14. Carrier existence check before deletion (InvalidOperationException when not found)
  15. Successful carrier deletion
  16. Repository DeleteAsync call verification
  17. UnitOfWork commit verification
  18. Orchestration order verification (Delete before Commit)
  19. No delete attempt when carrier not found
  20. Theory-based carrier ID scenarios
  21. Cancellation token support
  22. Error propagation tests (Delete, UnitOfWork failures)
  23. Verification that commit doesn't happen when delete fails

  24. UpdateWorkPieceCarrierHandler - 14 tests (Command handler with existence check)

  25. Constructor validation (3 tests)
  26. Carrier null validation (ArgumentException when carrier is null)
  27. Carrier existence check before update (InvalidOperationException when not found)
  28. Successful carrier update
  29. Repository SaveAsync call verification
  30. UnitOfWork commit verification
  31. Orchestration order verification (Save before Commit)
  32. No save attempt when carrier not found
  33. Theory-based scenarios (different carriers with various properties)
  34. Cancellation token support
  35. Error propagation tests (Save, UnitOfWork failures)
  36. Verification that commit doesn't happen when save fails

Query Handlers (4):

  1. GetAvailableWorkPieceCarriersHandler - 8 tests (Collection query handler)
  2. Constructor validation (2 tests for repository, logger)
  3. Successful retrieval of available carriers collection
  4. Repository GetAvailableAsync call verification
  5. Empty collection handling (returns empty, not null)
  6. Single carrier retrieval
  7. Multiple carriers retrieval (5 carriers with verification)
  8. Cancellation token support
  9. Error propagation

  10. GetWorkPieceCarriersByTypeHandler - 13 tests (Collection query handler with type filtering)

  11. Constructor validation (2 tests)
  12. Successful retrieval of carriers by type
  13. Repository GetByTypeAsync call verification with correct type parameter
  14. Empty collection handling
  15. Single carrier of specific type
  16. Multiple carriers of same type
  17. Theory-based carrier type scenarios (types 1, 2, 5, 10, 100)
  18. Cancellation token support
  19. Error propagation

  20. GetWorkPieceCarrierByIdHandler - 13 tests (Single query handler with KeyNotFoundException)

  21. Constructor validation (2 tests)
  22. Successful carrier retrieval by ID
  23. Repository GetByIdAsync call verification with correct ID
  24. Carrier not found handling (KeyNotFoundException with carrier ID in message)
  25. No null return verification (throws exception instead)
  26. Theory-based carrier ID scenarios (various IDs and carrier numbers)
  27. Theory-based capacity scenarios (carriers with different capacities)
  28. Cancellation token support
  29. Error propagation

  30. GetWorkPieceCarrierByRfidHandler - 28 tests (Single query handler with RFID lookup)

  31. Constructor validation (2 tests)
  32. Successful carrier retrieval by RFID tag
  33. Repository GetByRfidAsync call verification with correct RFID
  34. RFID not found handling (KeyNotFoundException with RFID tag in message)
  35. No null return verification
  36. Theory-based RFID tag scenarios (various tag formats: RFID-001, TAG-12345, etc.)
  37. Theory-based carrier capacity scenarios
  38. RFID format variations testing (UPPERCASE, lowercase, MiXeD, with_underscores, with-dashes)
  39. Cancellation token support
  40. 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):

  1. GetParameterSetupHandler - 7 tests (Generic query handler returning nullable TSetup)
  2. Constructor validation (1 test for repository dependency)
  3. Successful setup retrieval by version UID and mapping name
  4. Setup not found handling (returns null, not exception)
  5. Theory-based parameter scenarios (various version UIDs and mapping names across all 11 parameter systems)
  6. Repository parameter verification
  7. Cancellation token support
  8. Error propagation

  9. GetParameterMappingHandler - 8 tests (Generic query handler returning nullable TMapping)

  10. Constructor validation (1 test)
  11. Successful mapping retrieval by version UID and mapping name
  12. Mapping not found handling (returns null)
  13. Theory-based scenarios (TH, SC, EGP, RFL, CMMT, XGX system variations)
  14. Repository parameter verification
  15. Multiple calls with consistent results
  16. Cancellation token support
  17. Error propagation

  18. GetMappingsForVersionHandler - 10 tests (Collection query handler)

  19. Constructor validation (1 test)
  20. Successful retrieval of all mappings for a version
  21. Theory-based version UID scenarios
  22. Empty collection handling (returns empty, not null)
  23. Single mapping retrieval
  24. Multiple mappings retrieval (5 mappings with verification)
  25. Repository parameter verification
  26. Never returns null verification
  27. Cancellation token support
  28. Error propagation

Command Handlers (6):

  1. CreateParameterSetupHandler - 8 tests (Command handler returning created UID)
  2. Constructor validation (1 test)
  3. Successful setup creation with UID return
  4. Theory-based setup scenarios (various parameter types and values)
  5. Repository call verification (CreateSetupWithCrcAsync method)
  6. Multiple creations with different UIDs
  7. Cancellation token support
  8. Error propagation

  9. UpdateParameterSetupHandler - 7 tests (Simple command handler)

  10. Constructor validation (1 test)
  11. Successful setup update operations
  12. Theory-based parameter scenarios (various UIDs and setup data)
  13. Repository parameter verification
  14. Multiple updates handling
  15. Cancellation token support
  16. Error propagation

  17. CreateParameterMappingHandler - 13 tests (Command handler with business logic validation)

  18. Constructor validation (1 test)
  19. Uniqueness validation: Duplicate mapping detection (InvalidOperationException)
  20. Successful mapping creation with UID return
  21. Theory-based duplicate mapping scenarios
  22. Orchestration order verification: Existence check before creation
  23. Repository call verification (MappingExistsAsync + CreateMappingWithCrcAsync)
  24. Error propagation (during existence check and during creation)
  25. Cancellation token support

  26. UpdateParameterMappingHandler - 7 tests (Command handler with changelog tracking)

  27. Constructor validation (1 test)
  28. Successful mapping update with changelog
  29. Theory-based parameter scenarios
  30. Repository call verification (UpdateMappingWithChangelogAsync method)
  31. Multiple updates handling
  32. Cancellation token support
  33. Error propagation

  34. DeleteParameterMappingHandler - 7 tests (Simple delete command handler)

  35. Constructor validation (1 test)
  36. Successful mapping deletion by UID
  37. Theory-based UID scenarios
  38. Repository parameter verification
  39. Multiple deletions handling
  40. Cancellation token support
  41. Error propagation

  42. DeleteMappingsForVersionHandler - 8 tests (Cascade delete command handler)

  43. Constructor validation (1 test)
  44. Successful deletion of all mappings for a version (cascade delete)
  45. Theory-based version UID scenarios
  46. Repository parameter verification
  47. Multiple version deletions handling
  48. Used during version deletion to cascade parameter cleanup
  49. Cancellation token support
  50. 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 4. Nullable Query Handlers: Setup and Mapping query handlers return null when not found (different from other bounded contexts that throw KeyNotFoundException) 5. Collection Query Handlers: GetMappingsForVersionHandler returns empty collections (never null) when no mappings exist 6. Business Logic Validation: CreateParameterMappingHandler validates mapping uniqueness before creation (InvalidOperationException for duplicates) 7. CRC Calculation: Create operations use "WithCrc" methods (CreateSetupWithCrcAsync, CreateMappingWithCrcAsync) for data integrity 8. Changelog Tracking: UpdateParameterMappingHandler uses UpdateMappingWithChangelogAsync for audit trail 9. Cascade Delete Pattern: DeleteMappingsForVersionHandler supports version deletion by cleaning up all related parameter mappings 10. Test DTO Accessibility: Test DTOs must be public (not private) for Moq to create proxies for generic interfaces 11. Theory-Based Testing: Extensive use of [Theory] with [InlineData] for testing across multiple parameter system types 12. No Transaction Management: Parameters handlers don't use UnitOfWork - repository handles transaction management internally