Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 28 / 68

Checking Correctness (Your First Step into Testing)

In this lesson you will learn a simple way to verify behaviour and pick up the basic idea behind testing. This is for anyone searching for "PHP assert how to use" or "PHP testing how to write".

assert(condition) raises a warning when the condition is false. Checking automatically that a function returns the expected result is the basic idea behind test code. In practice you would use a dedicated framework such as PHPUnit, but the underlying thinking is the same as what you learn here.

The sample code checks the condition add(2, 3) === 5 with an if statement, printing "Test passed" when it holds and "Test failed" otherwise. That simple comparison of expected and actual result is your first step into testing.

A common stumbling block for beginners is that the assert function itself is not used much in real code. Assertions are a debugging aid during development, not a substitute for production error handling. Serious testing uses dedicated tools.

Getting into the habit of checking each function you write with a quick condition makes later changes and refactoring far less nerve-racking. Picking up the testing mindset early pays off enormously in practice.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)