我正在尝试使用Laravel 5.2设置PHPunit . 我按照文档进行了简单的单元测试,但每次测试都会抛出相同的错误:
1)CreateAccountTest :: testCreateUserWithInvalidEmail BadMethodCallException:调用未定义的方法Illuminate \ Database \ Query \ Builder :: make()/some/path/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php:2405 / some / path / vendor / laravel / framework / src / Illuminate / Database / Eloquent / Builder.php:1426 /some/path/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php:3526 / some / path / vendor / laravel / framework / src / Illuminate / Foundation / Testing / Concerns / MakesHttpRequests.php:504 /some/path/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/MakesHttpRequests.php:504 / some / path / vendor / laravel / framework / src / Illuminate / Foundation / Testing / Concerns / MakesHttpRequests.php:73 /some/path/tests/UnitTests/CreateAccountTest.php:32
我的单元测试看起来都类似于此,除了它每次声明一个不同的属性:
class CreateAccountTest extends TestCase
{
protected $body;
protected $app;
protected function setUp() {
parent::setUp();
$this->app = factory(\App\Models\App::class)->create([
'name' => 'Test Suite'
]);
$this->body = [
'name' => 'Doe',
'firstName' => 'John',
'login' => 'john.doe',
'email' => 'john.doe@johndoe.com',
'password' => 'test1324',
'repeatPassword' => 'test1234',
'appId' => $this->app->id
];
}
public function testCreateUserWithInvalidEmail() {
$this->body['email'] = 'this_is_not_a_valid_email_address';
$this->json('POST', '/profile/create', $this->body)
->assertResponseStatus(400);
}
}
包含相关代码的Profile控制器:
<?php
namespace App\Http\Controllers\Account;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\Account\CreateAccountPostRequest;
use App\Models\AccessToken;
use App\Models\User;
class ProfileController extends Controller
{
public function createUser(CreateAccountPostRequest $request) {
$user = new User();
$user->firstname = $request['firstName'];
$user->name = $request['name'];
$user->email = $request['email'];
$user->password = $request['password'];
$user->save();
$accessToken = AccessToken::createAccessToken($user->id);
$accessToken->save();
return $this->sendSuccessResponse();
}
}
模型工厂:
$factory->define(App\Models\App::class, function (Faker\Generator $faker) {
$company = $faker->company;
return [
'name' => $company,
'submit_description' => $faker->sentence($nbWords = 6, $variableNbWords = true),
'subdomain' => str_replace(' ', '', $company),
'advancedFilter' => 0,
'isdeleted' => 0,
'defaultlanguage' => 'en',
'timestamp' => time()
];
});
stacktrace所述的第32行是以下行:
$this->json('POST', '/profile/create', $this->body)
->assertResponseStatus(400);
根据文档,这一切似乎都非常简单,我不知道这里发生了什么 .
1 回答
好的,我弄明白这里发生了什么 . 我创建了一个字段
protected $app;
,它意外地覆盖了父TestCase
类的$ app字段 . 这将类从Laravel应用程序(Illuminate\Foundation\Application
)转换为Illuminate/Database/Eloquent/Model
,其中make()函数不存在 . 这就是抛出错误的原因 .所以基本上,将
$app
字段重命名为$application
或其他任何内容都可以解决问题 .