April 5, 2018

What is a unit test?

A unit test is a test that checks to see if a class - or a method on a class - does what it’s supposed to do.

It’s really that simple.

Let’s say we have a class that uploads an image to Amazon S3.

(The syntax is php and Laravel)


class UploadImageToS3
    protected $image;

    public function __construct($image)
        $this->image = $image;

    public function upload()
        Storage::disk('s3')->put('images', $this->image);

We want to confirm the upload method works, so we’ll write a unit test.

public function uploads_a_video_to_s3()
    // Fake the upload to S3, and save it locally instead

    // Laravel generates a fake image
    $image = UploadedFile::fake()->image('image.jpg');

    $uploader = new UploadImageToS3($image);

    // Assert that the file was uploaded. Laravel generates an  // md5 hash for the file name, and saves it under that hash     // rather than the original name.


That’s it!

You have a unit test.

When writing tests, it’s ideal to write mostly unit tests, with some acceptance (feature) tests scattered about. In Gary Bernhardt’s talk “Fast Test Slow Test”, he suggests a ration of 9 to 1 (unit tests - feature tests).

The reason you want to write more unit tests than acceptance (feature) tests, is that unit tests are faster. And we want our test suite to run quickly.

I’m kind of getting into another topic, so I’ll stop here.

Don’t get hung up on the 9-1 ratio, or acceptance (feature) tests. The important part is to understand what a unit test is, a test that exercises a single class or method to confirm it works.

Are you new to Test Driven Development?

Join the mailing list! :)