Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test namespaced objects in Laravel 4 with phpunit

I'm organizing my tests folder to reflect the namespaced objects and interfaces in my app. However, I've been running into nothing but trouble trying to maintain order while practicing TDD with namespaces! I'm completely at a loss of how to get all these pieces to play nice. Any help with this issue would be greatly appreciated!

Structure:

app/ 
  Acme/ 
    Repositories/ 
      UserRepository.php 
    User.php
  tests/ 
    Acme/ 
      Repositories/ 
        UserRepositoryTest.php 
      UserTest.php

app/Acme/User.php

<?php namespace Acme;

use Eloquent;

class User extends Eloquent {

    protected $guarded = array();

    public static $rules = array();
}

app/tests/Acme/UserTest.php

<?php

use Acme\User;

class UserTest extends TestCase {

    public function testCanBeLoaded()
    {
        $this->assertInstanceOf(User, new User);
    }
}

PHPUnit result:

1) UserTest::testCanBeLoaded
ErrorException: Use of undefined constant User - assumed 'User'
like image 901
bkimball Avatar asked Feb 01 '26 00:02

bkimball


1 Answers

The assertInstanceOf method expects a string, not an object. Try User::class. The ::class notation was introduced in PHP 5.5

<?php

use Acme\User;

class UserTest extends TestCase
{
    public function testCanBeLoaded()
    {
        $this->assertInstanceOf(User::class, new User);
    }
}

Update 22/11/2015

Updated my answer to a better solution with today's best practices in PHP.

like image 109
Dries Vints Avatar answered Feb 02 '26 13:02

Dries Vints



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!