Unit Tests

What is Unit Testing?

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 ecommerce 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 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.

Why do we need Unit Tests?

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 lot of possibilities of tests cases, but it is important keep the test cases to a minimum and to the point. 

As a best practice, it is better to include test cases which 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.

  • Unit testing saves time and money.
  • Reduces defects in the newly developed features or reduces bugs when changing the existing functionality.
  • Improves design and allows better refactoring of code.
  • Unit Tests, when integrated with build ensure the quality of the build.
  • Prevent malfunctioning behavior of edge cases, which may go unnoticed in development.

Standard Unit Testing vs WordPress Unit Testing

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 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 WordPress Environment in isolation, hence we are calling it as Unit Tests.