A Quick Intro to Automated Testing

Coding (Test automation)


Learn how to write automated tests and make you code safe using PHPUnit
 
/img/blog/a-quick-intro-to-automated-testing.jpeg

TL;DR

 

  • Lack of testing causes projects to become unmanageable
  • There are different types of testing
  • It takes 5 seconds to begin
  • Use the Given-When-Then style

 

Who is this article for?

 

In this article, you will understand the principle of testing and a few basic but important keywords.

 

To understand this post you need to know what Composer is.

 

If you don’t, here is the article for you:

Introduction to Composer [installation and components]

 

 

Why write tests?

 

One thing you need to understand straight away.

 

If you are a programmer, I don’t care what language you code in, testing is as important as the code itself

 

… and I can speak from personal experience.

 

Let me explain.

 

My only task at my current job is to refactor a project that has some old, what I’m saying old, ancient code.

 

If you consider 1 dog year is 15 human years, in tech years this project would be prehistoric for us.

 

Only a few know how it works and the codebase is too delicate to not break things, business-critical things.

 

The result is that no one is allowed to touch it.

 

“Deleting code is sometimes hard, but so rewarding.” — Sebastian Bergmann

 

We arrived at this situation only for one reason:

 

The lack of testing!

 

People that do not use automated testing usually write some new code or refactor old ones, then open the browser and check if everything works.

 

In some cases, depending on where you work you might have a team of QA there to help you.

 

This is good but not flawless because you can lose some details while testing this way.

 

Plus ideally, you want to automate this process.

 

When you finish writing tests you know that they work.

 

If one day, years from now you update something and one of those tests fails you know you did something you shouldn’t have done.

 

This allows you to work even with very old code.

 

In fact, now, you will have the confidence that, if you screw up, those tests are going to tell you how and you can fix it back.

 

So why so many people do not want to do it?

 

The reality?

 

Testing can be boring, and it takes a lot of time.

 

“The problem is not that testing is the bottleneck. The problem is that you don’t know what’s in the bottle. That’s a problem that testing addresses.“ — Michael Bolton

 

Take it this way

 

It is amazing to see colorful cakes and sweets at your favorite restaurant right?

 

But to look so nice and taste so good, you need many hours in the kitchen to find the best combination of ingredients.

 

 

 

 

Types of Testing

 

To spice up the ‘testing’ menu, there are many different types of tests and processes that you can choose to use.

 

Here are the most popular ones

 

* Unit testing

 

These tests ensure that individual units of code, for example, a single class or even a single method work as intended.

 

Given the small amount of code we are testing this type is the easiest to write.

 

* Integration testing

 

They test a combination of classes and commonly interact with a big chunk of the application.

 

Bare in mind, that these tests do not yet cover the full working application.

 

They only assure that a single functionality works fine.

 

Since you might need some class to be mocked and, in some cases, you might need a connection to the database too this type of test is a bit more complex.

 

*Application tests

 

These tests check the behavior of a complete application.

 

They make HTTP requests and test that the response is the same as the one we expect.

 

Here we definitely make use of HTTP requests, databases, mock, and other tools.

 

* TTD

 

This acronym stands for Test-driven development.

 

What it means is that tests are written beforehand.

 

It works like a cycle,

 

  1. You write the tests, stating what you are expected to have as an end result;
  2. Then run the test;
  3. The tests fail because there is no code to back them up
  4. You start implementing the code until the tests works

 

The full explanation here by Sameer Nyaupane

 

* BDD

 

In behavior-driven development, tests are written beforehand too.

 

It works the same as TTD but instead of writing test cases, you write behavior in English.

 

Check Behat for more information

 

Installation

 

It’s time to get your feet wet.

 

PHPUnit requires PHP 7.3 plus the dom and JSON extensions.

 

Usually, those two extensions are enabled by default.

 

The code coverage (that we’ll see in another post) requires Xdebug.

 

There are many ways to install PHPUnit into your machine.

 

My favorite one is by using Composer, to do so just copy the following command into your terminal and press enter.


composer require --dev phpunit/phpunit ^9.5

 

Easy right?

 

As you can see we install this tool only as a development dependency as we do not need it on production.

 

Now, It is common to install PHPUnit globally and have it working everywhere but this is not the best way to work with it.

 

Instead, it should be used as a project-local dependency.

 

To verify that it was actually installed open the composer.json file at the root of your project and check if you find these lines.


"require-dev": {
    "phpunit/phpunit" :"^9.5"
}

 

This is only to check if Composer understood what we wanted,

 

You can also check if the executable file is in vendor/bin/phpunit.

 

How to test

 

Now that we have the basics covered let’s talk about how to actually do it.

 

“No amount of testing can prove a software right, a single test can prove a software wrong.” — Amir Ghahrai

 

A popular way to test is the GIVE-WHEN-THEN method.

 

Here is an example.

 

Step-by-step.

 

Imagine an application that manages groceries lists.

 

The user fills out a form with a list of products he needs to buy and then our app shows him the best price and where to buy it.

 

What we need to make this work is an array of products to send to our third-party API.

 

What we get from the user is a comma-separated list of elements.

 

We might need a parser that transforms this string into an array, and we must test if it works all the time.

 

First thing first,

 

we define our GIVE-WHEN-THEN.


public function test_grocery_list_becomes_array()
{
    // Given we have a string cointaining a list of items
    // When the list goes through the parser
    // Then we obtain an array of products
}

 

This is good!

 

We know our requirements, and we know what the end product will be.

 

Time to update the test with some real code.

 

public function test_grocery_list_becomes_array()
{
    // Given we have a string cointaining a list of items
    $userList = 'broccoli, chicken, water, potatoes, beans';    $expectedResult = ['broccoli', 'chicken', 'water', 'potatoes', beans'];    // When the list goes through the parser
    $listParser = new ListParser;
    $result = $listParser->parse($userList);    // Then we obtain an array of products
    assertEquals(expectedResult, $result);
}

 

Notice that we haven't written a single line of actual ListParser’s code.

 

“Testing is a skill. While this may come as a surprise to some people it is a simple fact.” — Fewster and Graham

 

At this point, we haven’t even created the ListParser class.

 

We are sure of what we have to build though,

 

we know that once implemented the code will do what we want and it will be already tested.

 

Conclusion of Pt.1

 

You’ve seen why testing is incredibly important and how easy is to start with it.

 

Implementing automated testing into your coding journey not only will make your project more secure and ready to be refactored.

 

It will speed up your career too.

 

In the next part of the series, we’ll dive deeper into the code with plenty of examples and many techniques.

 
 
If you like this content and you are hungry for some more join the Facebook's community in which we share info and news just like this one!

Other posts that might interest you

Coding (Test automation) Nov 13, 2022

How to Do Testing with Postman

See details
Coding (Test automation) Jul 14, 2023

4 steps to getting started with Behaviour-Driven Development

See details
Coding (Test automation) Jul 16, 2023

How to implement Behat into your PHP project

See details
Get my free books' review to improve your skill now!
I'll do myself