作者:创业语录分享_689 | 来源:互联网 | 2023-02-10 14:24
我尝试为我User
和Shop
模型之间的关系创建单元测试,但是当我运行vendor\\bin\\phpunit
这个错误时,我不知道这个,因为我是单元测试的新手.我试图在我的控制器上运行我的代码以查看关系是否真的有效,幸运的是它按预期工作,但在phpunit中运行时却没有.这个phpunit没有与Models一起工作,我做错了什么?
Fatal error:
Uncaught Error: Call to a member function connection() on null in E:\projects\try\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php:1013
Stack trace:
E:\projects\try\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php(979): Illuminate\Database\Eloquent\Model::resolveConnection(NULL)
这是我的UserTest.php
setUp();
}
function setUp()
{
$user = new User([
'id' => 1,
'first_name' => 'John',
'last_name' => 'Doe',
'email' => 'JohnDoe@example.com',
'password' => 'secret',
'facebook_id' => null,
'type' => 'customer',
'confirmation_code' => null,
'newsletter_subscription' => 0,
'last_online' => null,
'telephone' => null,
'mobile' => null,
'social_security_id' => null,
'address_1' => null,
'address_2' => null,
'city' => null,
'zip_code' => null,
'signed_agreement' => 0,
'is_email_confirmed' => 0
]);
$user = User::find(1);
$shop = new Shop([
'id' => 1,
'user_id' => $user->id,
'name' => 'PureFoods Hotdog2',
'description' => 'Something that describes this shop',
'url' => null,
'currency' => 'USD'
]);
$user->shops()->save($shop);
$shop = new Shop([
'id' => 2,
'user_id' => $user->id,
'name' => 'PureFoods Hotdog',
'description' => 'Something that describes this shop',
'url' => null,
'currency' => 'USD'
]);
$user->shops()->save($shop);
$this->user = $user;
}
/** @test */
public function a_user_has_an_id(){
$user = User::find(1);
$this->assertEquals(1, $user->id);
}
/** @test */
public function a_user_has_a_first_name(){
$this->assertEquals("John", $this->user->first_name);
}
/** @test */
public function a_user_can_own_multiple_shops(){
$shops = User::find(1)->shops()->get();
var_dump($this->shops);
$this->assertCount(2, $shops);
}
}
看来,这个错误是由这行代码引起的:
$user->shops()->save($shop);
- 这个代码在我的示例路由或Controller中运行时实际工作,但errors
在运行时抛出phpunit
user.php的
hasMany('App\Shop');
}
}
Shop.php
belongsTo('App\User');
}
}
任何帮助将非常感谢.谢谢!
1> 小智..:
首先,在每次测试之前调用setUp(),因此不应该在构造函数中调用它
其次,您应该在setUp()中调用parent :: setUp()来初始化app实例.
2> 小智..:
例:
user = \App\User::first();
}
public function testExample()
{
$this->assertEquals('victor@castrocontreras.com', $this->user->email);
}
}