I tried creating a unit test for the relationships between my User
and Shop
models, however when I run vendor\\\\bin\\\\phpunit
this e
First of all, setUp()
is called before every test, so you shouldn't call it from within the constructor
Second of all, you should call the parent::setUp()
in your setUp()
to initialize the app instance.
Cause of the problem: you can't use Laravel Models functionality from code called in the constructor of Class UserTest - even though you put the code in the method "setUp", you unnecessarily called it from the constructor. SetUp is called by phpUnit without you needing to do it in the constructor.
When the UserTest constructor has run, the Laravel Bootstrap code has not yet been called.
When the UserTest->setUp() method is called, the Laravel Bootstrap code HAS been run, so you can use you Models etc.
class UserTest extends TestCase
{protected $user, $shop;
function __construct()
{
$this->setUp(); // **THIS IS THE PROBLEM LINE**
}
function setUp()
{
$user = new User([....
Example:
<?php
class ExampleTest extends TestCase
{
private $user;
public function setUp()
{
parent::setUp();
$this->user = \App\User::first();
}
public function testExample()
{
$this->assertEquals('victor@castrocontreras.com', $this->user->email);
}
}
One more reason
check if the test class is extending use Tests\TestCase; rather then use PHPUnit\Framework\TestCase;
Laravel ships with the later, but Tests\TestCase class take care of setting up the application, otherwise models wont be able to communicate with the database if they are extending PHPunit\Framework\TestCase.
That can be happens when you try to read database from dataprovider function. Like me tried, yes. The work way:
protected static $tariffs_default;
protected function setUp(): void {
parent::setUp ();
if (!static::$tariffs_default){
static::$tariffs_default = DB::...;
}
}
// in dataprovider we use string parm, named as our static vars
public static function provider_prov2(){
return [
[".....", [ 'tariffs'=>'tariffs_default'] ],
];
}
// then, in test we can ask our data by code:
public function testSome(string $inn, string $ogrn, $resp_body){
if ( $ta_var = Arr::get( $resp_body, 'tariffs' ) ){
Arr::set($resp_body, 'tariffs', static::$$ta_var );
}
$this->assert...
}
You are assigning the id '2' to both shops.
Assigning is should not be neccessary since I assume the shop table id field is an autoincrement field.
Also look into database factories in the Laravel docs, it will simplify things for you.