PHPUnit is a framework-independent library for unit testing PHP. Unit testing is a method by which small units of code are tested against expected results.
With unit testing we test each component of the code individually. All components can be tested at least once. A major advantage of this approach is that it becomes easier to detect bugs early on. The small scope means it is easier to track down the cause of bugs when they occur.
As an example, imagine we have an e-commerce website. We might traditionally test this by opening the site in the browser, searching for a product, then adding this to the basket and checking the basket total to see if it looks as we’d expect. If we were to unit test this process, we might write a test to ensure we can search for a specific product, write another to ensure we can add a product to the basket, and then another test to ensure that the basket total sums correctly.
Unit tests are written so that many bugs are found at the development stage, which prevents the transition of these bugs to the following stages, including after the release of the product.
There are a lot of possibilities for test cases, but it is important to keep the test cases to a minimum and to the point.
As a best practice, it is better to include test cases that have an important `business logic`, `feature`, `behavior` etc. so that it’s `functionality` or `behavior` will not be altered unintentionally in development, as the tests will fail if it happens.
This saves the costs of fixing the bugs later in the development life cycle and brings benefits to end-users, who don’t have to deal with a buggy product.
Also, you will benefit from improved test time estimation, saving lots of time and resources.
WordPress Unit Tests use database and WordPress API functions in order to run tests. This is not exactly testing in perfect isolation, but we are testing it in isolation with the WordPress environment.
This is usually referred to as Integration Tests where other functions and methods can be used in order to test integration of the code. As we are testing the code with respect to the WordPress environment in isolation, we are calling it a “unit test.”