0

I was writing unit tests for an entity like this:

class Image
{
    /**
     * @var string
     */
    private $name;

    /**
     * @var string
     */
    private $path;

    /**
     * @return string
     */
    public function getUrl()
    {
        return $this->getPath() . $this->getName();
    }

    /**
     * @return string 
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @return string 
     */
    public function getPath()
    {
        return $this->path;
    }
}

As you can see the getUrl()method returns a string formed of pathand name.

This is the code to test it:

class ImageTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Tests all get and set methods
     */
    public function testImage()
    {
        $resource = new Image();

        $test = array(
            'name' => 'testName.jpg',
            // Set this without the ending slash (/)
            'path' => 'path/to/image',
        );

        $test['url'] = $test['path'] . $test['name'];

        $this->assertEquals($test['name'],       $resource->getName());
        // Check that, when set, a slash (/) is added at the end of the Path
        $this->assertEquals($test['path'] . '/', $resource->getPath());
        $this->assertEquals($test['url'],        $resource->getUrl());
    }
}

As you can see, first has to be created the array, then it is possibile to set $test['url'].

At this point the curiosity because I were writing, instead, something like this:

$test = array(
    'name' => 'testName.jpg',
    'path' => 'path/to/image',
    'url'  => $test['path'] . '/' . $test['name']
);

But this syntax returns this error:

There was 1 error:

1) Tests\Entity\ImageTest::testImage Undefined variable: test

Maybe is there something like the self statement for Objects?

1 Answer 1

1

No. The array isn't defined until $test = array(...); command completes.

$test = array(
    'name' => 'testName.jpg',
    'path' => 'path/to/image',
);

$test['url'] = $test['path'] . '/' . $test['name'];

It doesn't look as nice as what you're trying to do, but that's the correct way to do it.

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

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.