af1223345
af1223345

Reputation: 45

Including test in PHPUnit

I started to use PHPUnit, and in my first test I don't understand why I have to use require "app/Slug.php"; instead of require "../app/Slug.php";

enter image description here

and this is the test code:

<?php

    use PHPUnit\Framework\TestCase;

    class SlugTest extends TestCase{

        public function test_render(){
            require "app/Slug.php";

            $slug = new Slug("My First Test");

            $this->assertEquals($slug->render(), "my-first-test");
        }
    }

I thought that I could use require "../app/Slug.php"; to make it work. I even tested the route in the console but the code only works with require "app/Slug.php";

Does anyone know why?

Upvotes: 1

Views: 78

Answers (2)

krylov123
krylov123

Reputation: 772

That's correct behaviour, because you run tests from project root directory. So current work directory is project's root folder. require will try to include relative paths using current directory as base path.

If you use require "../app/Slug.php"; then you should run phpunit from the tests folder.

Like this:

# that way it will work with "../app/Slug.php"
cd tests
./../vendor/bin/phpunit SlugTest.php --color

So, the base path is not where the file is lying, but where you run it from.

Upvotes: 0

Mohammed Hamid Hamoda
Mohammed Hamid Hamoda

Reputation: 111

Yes You Need To require app/Slag.php to load a class or code inside it and access it from test file. but you can use composer to autoload your Classes via psr-4 or files

Upvotes: 1

Related Questions