0

I'm new to PHPUnit, and unit testing in general. I can't seem to find a clear tutorial or resource on how best to test:

  1. Passing no argument fails.
  2. How to pass an argument for a constructor test.
  3. Passing an empty argument results in the expected exception.

How would I approach testing this constructor?

<?php

class SiteManagement {
    public function __construct (array $config) {
        // Make sure we actually passed a config
        if (empty($config)) {
            throw new \Exception('Configuration not valid', 100);
        }

        // Sanity check the site list
        if (empty($config['siteList'])) {
            throw new \Exception('Site list not set', 101);
        }
    }
}
1
  • new SiteManagement ( $configarray ); Commented Apr 7, 2021 at 21:30

2 Answers 2

3

The example 2.11 of the PHPUnit documentation shows how to test exceptions.

For your specific class, it would be something like this:

$this->expectException(Exception::class);

$object = new SiteManagement([]);

You shouldn't test if the method fails without arguments unless those arguments are optional. This would be out of the scope for a unit test.

Sign up to request clarification or add additional context in comments.

Comments

1

A good test battery for your class would be:

/** @test */
public function shouldFailWithEmptyConfig(): void
{
    $config = [];

    $this->expectException(\Exception::class);
    $this->expectExceptionMessage('Configuration not valid');
    $this->expectExceptionCode(100);

    new SiteManagement($config);
}

/** @test */
public function shouldFailWithoutSiteListConfig(): void
{
    $config = ['a config'];

    $this->expectException(\Exception::class);
    $this->expectExceptionMessage('Site list not set');
    $this->expectExceptionCode(101);

    new SiteManagement($config);
}

/** @test */
public function shouldMakeAFuncionality(): void
{
    $config = [
        'siteList' => '',
    ];

    $siteManagement = new SiteManagement($config);

    self::assertSame('expected', $siteManagement->functionality());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.