Before writing tests, learn the basic words first. A test usually creates something, runs code, and checks the result. In this project, that check is done with small assert methods.
Summary: Learn the words and patterns used in the other lessons.
Here is the basic pattern we want to understand:
// Arrange
$number = 2 + 2;
// Act
$result = $number;
// Assert
$this->assertSame(4, $result);
Now here is a very small example test:
// PHP built-in assert()
assert(4 === 4);
// Exact same value and type.
$this->assertSame(4, 4);
// Condition must be true.
$this->assertTrue(4 > 1);
// One string must contain the other.
$this->assertStringContains('API', 'Integration Test (API)');Why this test works
- Arrange means: prepare the object or value you need.
- Act means: run the code you want to test.
- Assert means: check whether the result is what you expected.
- PHP also has a built-in assert() function, for example assert($number === 4).
- In this project we mostly use assertSame(), assertTrue(), and assertStringContains() because they give clearer test messages.
- assertSame($expected, $actual) means both value and type must match exactly.
- assertTrue($condition) means the condition must be true.
- assertStringContains($needle, $haystack) means one text must exist inside another text.
- Use this lesson first if the other examples feel too fast.
Real-life examples
- Example: on a blog website, check that the page title text is exactly "My Articles".
- Example: on a dashboard website, check that the user role is exactly "admin" after login data is loaded.
Official docs
Remember this
- Arrange = prepare
- Act = run the code
- Assert = check result
- assertSame = exact match
- Start here before Unit Test
Run this learning module with:
Read this lesson in the browser first, then continue with php tests/run.php unit