Skip to content

Latest commit

 

History

History
42 lines (33 loc) · 1.27 KB

File metadata and controls

42 lines (33 loc) · 1.27 KB

Step 7: Basic Tests

Testing is not optional. In professional software engineering, if it's not tested, it's broken.

Why Test?

  1. Regression Prevention: When you add features later, tests ensure you didn't break existing ones.
  2. Documentation: Tests show exactly how the code is expected to behave.
  3. Confidence: You can refactor code without fear.

Unit Testing in C

We implemented a simple unit test for the Scanner in tests/test_scanner.c.

Anatomy of a Test

void test_scenario() {
    // 1. Arrange (Setup)
    const char *input = "ABC";
    Scanner scanner;
    scanner_init(&scanner, input);

    // 2. Act (Do something)
    char result = scanner_next(&scanner);

    // 3. Assert (Check result)
    assert(result == 'A');
}

The assert Macro

We use <assert.h>. If assert(condition) fails, the program crashes immediately with an error message. This is perfect for development testing.

Running Tests

We added a test target to the Makefile.

make test

This compiles the test program, links it against our library, and runs it.

What you learned

  • Unit Testing: Testing small units (Scanner) in isolation.
  • Assertions: Using assert to enforce correctness.
  • Automation: Making tests run with a single command.