繁中EN

What is Test-Driven Development (TDD)?

Test-Driven Development (TDD) is an extremely focused, rigorous, and requirement-oriented software development methodology. It requires that test code must be born before actual functional code.

TDD Design Philosophy: Test-First

In traditional waterfall or agile development, developers are typically "write functional code first, then write tests when time permits", or even completely rely on manual testing (Test-Last).

TDD overturns this pattern.It treats "test scripts" as the concrete physical definition of requirements. Developers clarify boundary conditions, input/output specifications, and module interfaces by writing a test that is guaranteed to fail first; this ensures every line of code produced is solely to make tests pass, with no redundancy.

Development Mindset Showdown: Traditional Mode vs TDD Mode

Traditional Development (Test-Last)

  • Write code first, then manually add tests in a "piecing" manner
  • Code easily becomes highly coupled with the environment, making it extremely difficult to write automated tests later
  • When refactoring code, one is very cautious and fears that touching one part will affect everything else
  • Specification files age over time and cannot reflect the true implementation state of the code

Test-Driven (Test-First)

  • Write test scripts first, then write functional code that exactly meets requirements
  • Naturally enforces practice of concern separation and interface decoupling, improving architectural flexibility
  • Has a 100% automated self-test safety net, allowing bold refactoring anytime, anywhere
  • Test cases are "living documents" that always reflect actual expected behavior

Core Business Value Brought by TDD to Projects

1. Reduce defect leakage rate by 60% - 90%

Catch boundary errors and type anomalies early on, avoiding system defects leaking into expensive late-stage manual testing and online production environments.

2. Provide excellent system refactoring and upgrade flexibility

When software changes or patches are published, trigger automated regression tests with one click, ensuring "existing stable functions are not damaged by refactoring".

TDD Real-World Case Study: MES Work Order Package Confirmation System

This case study uses the (MES) manufacturing execution system as a basis,"Work Order Package Verification"as the object for development using the TDD methodology. The system is responsible for checking whether all static configurations (CheckList, Route) and dynamic resources (BOM inventory, equipment status, critical parts) are fully in place before work orders go to production.

1. MES Package Verification Data Source (Excel Content Description)

The system will load two Excel spreadsheets from external sources as input data, with internal structure and test data as follows:

Configuration file WO_validation.xlsx

Defines the required BOM quantities, process routes, critical components, and checklists for work orders:

BOM tab:
Parentcomponents (typo)usageunit
PRD-001A0.5kg
PRD-001B2.0kg
PRD-001C3.0kg
Route tab:
productSteplead time
PRD-001brend1.0
PRD-001casting1.0
PRD-001ovening2.0
PRD-001skiving0.5
Critical Component tab: PRD-001Requiredmod-001
Checklist tab: Machine avilibility: Y, SOP: Y

Status database inventory.xlsx

Tracks dynamic inventory and status in the production environment (equipment and critical component statuses have been corrected to OK):

Material(BOM) tab (multi-batch inventory):
Part numberbatchamount
Aa00019
Aa00028
Bb00018
Bb00026
Cc000113
Cc00028
Equipment tab (equipment status):
equipmentStatus
brendOK
castingOK
oveningOK
skivingOK
Critical Component tab:
Serial numberCRT0003/ Specificationmod-001/ StatusOK

2. Test-driven code structure (TDD Tests Structure)

This system has four test files, using tests to drive feature development:

3. Demo presentation and test execution (run_demo.py)

We can use the dedicatedrun_demo.pyto execute comprehensive checks, and display operational results on the host terminal:

# Run validation engine unit tests
$ python -m unittest discover -s tests
....................
----------------------------------------------------------------------
Ran 20 tests in 0.320s
OK

# Run actual Demo showcase program
$ python run_demo.py
Loading data from Excel sheets...
Data loaded successfully.

--- Test Case 1: Planned Quantity = 5 ---
Expected: True, Actual Result: True

--- Test Case 2: Planned Quantity = 10 ---
Expected: False, Actual Result: False

3.5. Work order input and validation engine call relationship (run_demo.py and validator.py)

When we executerun_demo.pythe program will first accept the input work order information (such as work order production quantity), then call the comprehensive validation enginevalidator.pyin which rules verified by unit teststest_validator.pyfor comparison. Below is this core call fragment:

# Excerpted from run_demo.py
# 1. Define work order planned quantities for validation (e.g., inputs 5 and 10)
iQtySuccess: int = 5
iQtyFail: int = 10

# 2. Directly call the unified kitting validation entry point defined in validator.py
# The business logic running behind this engine is protected by test cases in tests/test_validator.py
bResultSuccess: bool = validate_work_order_kitting(
    iPlannedQty=iQtySuccess,
    lstBOM=lstBOM,
    lstRoute=lstRoute,
    lstChecklist=lstChecklist,
    lstCCRequirements=lstCCReq,
    lstMaterialInv=lstMaterialInv,
    lstEquipInv=lstEquipInv,
    lstCCInv=lstCCInv
)

Note:This process demonstrates the execution of program (run_demo.py) and TDD development outcomes cooperation. Inrun_demo.pyafter setting input conditions, directly callvalidator.py. Since all core logic within this validator has already been thoroughly verified in unit teststest_validator.py(multi-batch inventory accumulation, each status as OK, etc.), we can directly trust its results in the Demo.

4. Domain entity and validation logic interaction code (using test_validator.py as an example)

In TDD development, we use unit tests to first define the interaction between domain models and validation logic. Below excerpted fromtests/test_validator.pyunit test fragment for validating BOM inventory:

# Excerpted from tests/test_validator.py
from src.domain.models import BOMItem, MaterialInventory
from src.domain.validator import validate_bom_inventory

def test_bom_inventory_sufficient_should_pass(self) -> None:
    # Arrange - Define work order quantity and BOM usage requirements (using domain entities from models.py)
    iPlannedQty: int = 10
    lstBOM: list[BOMItem] = [
        BOMItem(sParentProduct="PRD-001", sMaterialId="A", dUsage=0.5, sUnit="kg"),
        BOMItem(sParentProduct="PRD-001", sMaterialId="B", dUsage=2.0, sUnit="kg")
    ]
    # Define simulated inventory state (composed of MaterialInventory entities)
    lstInventory: list[MaterialInventory] = [
        MaterialInventory(sMaterialId="A", sBatchId="a1", dAmount=3.0),
        MaterialInventory(sMaterialId="A", sBatchId="a2", dAmount=3.0),
        MaterialInventory(sMaterialId="B", sBatchId="b1", dAmount=15.0),
        MaterialInventory(sMaterialId="B", sBatchId="b2", dAmount=10.0)
    ]
    
    # Act - Call the validation logic under test
    bIsBOMOk: bool = validate_bom_inventory(
        iPlannedQty=iPlannedQty,
        lstBOM=lstBOM,
        lstInventory=lstInventory
    )
    
    # Assert - Verify result matches expectation (must be True)
    self.assertTrue(bIsBOMOk)

Note:This fragment demonstrates how the test program actively instantiates inmodels.pydefined data structures, and passes them as parameters tovalidator.pyfunction for validation. When writing this test,validate_bom_inventorydid not yet exist (or only had a stub returning False), which forced developers to first establish the function's parameter interface and types before writing actual code.

5. Integration and Excel loading verification code (using test_integration.py as an example)

In E2E integration tests or demonstration scripts, we useloader.pyto read actual Excel files, and pass the parsed data list into the integrated comprehensive validation engine. Below excerpted fromtests/test_integration.pyTest snippet:

# Excerpted from tests/test_integration.py
from src.domain.loader import (
    load_bom_items, load_route_steps, load_checklist_items,
    load_critical_component_requirements, load_material_inventories,
    load_equipment_inventories, load_critical_component_inventories
)
from src.domain.validator import validate_work_order_kitting

class TestWorkOrderKittingIntegration(unittest.TestCase):
    def setUp(self) -> None:
        self.sValidationPath: str = r"c:\AI\Antigravity\anti\TDD_method\TDD\WO_validation.xlsx"
        self.sInventoryPath: str = r"c:\AI\Antigravity\anti\TDD_method\TDD\inventory.xlsx"

        # 1. Load actual Excel data via loader, with automatic column spelling mapping
        self.lstBOM = load_bom_items(self.sValidationPath)
        self.lstRoute = load_route_steps(self.sValidationPath)
        self.lstChecklist = load_checklist_items(self.sValidationPath)
        self.lstCCReq = load_critical_component_requirements(self.sValidationPath)
        self.lstMaterialInv = load_material_inventories(self.sInventoryPath)
        self.lstEquipInv = load_equipment_inventories(self.sInventoryPath)
        self.lstCCInv = load_critical_component_inventories(self.sInventoryPath)

    def test_e2e_sufficient_inventory_should_pass(self) -> None:
        # Arrange - Set planned production quantity to 5 (sufficient inventory per Excel)
        iPlannedQty: int = 5

        # Act - Call the single-entry kitting validation function
        bIsKittingComplete: bool = validate_work_order_kitting(
            iPlannedQty=iPlannedQty,
            lstBOM=self.lstBOM,
            lstRoute=self.lstRoute,
            lstChecklist=self.lstChecklist,
            lstCCRequirements=self.lstCCReq,
            lstMaterialInv=self.lstMaterialInv,
            lstEquipInv=self.lstEquipInv,
            lstCCInv=self.lstCCInv
        )

        # Assert - Verification result should be True (kitting passed)
        self.assertTrue(bIsKittingComplete)

Explanation:This integration test snippet showsloader.py and validator.pyfull collaboration. Loader is responsible for parsing out theBOMItem, RouteStepand other entity lists, and perfectly absorbs Excel such ascompoents and serail spelling errors, enabling Validator to perform clean, decoupled business rule judgments using standard English field naming.

6. System interaction and TDD mental diagram (Interaction & TDD Loop)

The following figure shows the interaction between the Excel file, loader, domain model, verification engine and test code (including Demo), as well as the Red-Green-Refactor cycle spirit followed by the TDD methodology:

Excel data source .xlsx files Excel loader loader.py domain entity model models.py Comprehensive verification engine validator.py Demo integrated executor run_demo.py / test_integration.py 1. RED Write failing tests 2. GREEN Minimum implementation passed 3. REFACTOR Optimize architecture reconstruction

Explanation:When the system is operating,run_demo.py(or integration test) driverloader.pyRead and convertExcelarchive, generatemodels.pyDomain model entities defined in thevalidator.pyThe inspection will be carried out and the final confirmation results will be sent back. In the development process, the TDD cycle of "red (failed test) $\rightarrow$ green (minimum implementation) $\rightarrow$ reconstruction (architecture optimization)" is always followed.

A safety net for TDD

This case fully demonstrates the essence of TDD: first establish test case protection boundaries and then implement functions. Under this development model, if we need to modify the Excel field correspondence, change the definition of equipment status, or optimize the multi-batch allocation logic in the future, we can immediately catch any logic loopholes by executing the test suite with one click, ensuring zero risk in reconstruction.