英文:
Laravel Tests assertEquals says Target class [request] does not exist
问题
我正在编写一个类似于Laravel的测试,如下所示(仅相关部分):
namespace Tests\Feature\Response;
use App\Models\Customer;
use Tests\TestCase;
class ResponseTest extends TestCase
{
protected $customer;
public function setUp(): void
{
parent::setUp();
$this->customer = Customer::factory()->enabled()->create();
}
public function testJson(): void
{
$responseData = (object) ['code' => 'NOT OK'];
// Test its response
$this->assertEquals('OK', $responseData->code, 'response data did not respond OK');
}
}
但是,它不是返回消息 "response data did not respond OK",而是返回 "Target class [request] does not exist"。
工厂的相关部分如下:
public function enabled()
{
return $this->state(function (array $attributes) {
return [
'enabled' => 1
];
});
}
Customer
模型的相关部分如下:
public static function boot()
{
parent::boot();
$request = request();
}
奇怪的是:当我不使用状态 "enabled()" 时,问题就不会出现。我做错了什么?
英文:
I am writing a test in Laravel like this (only the relevant part):
namespace Tests\Feature\Response;
use App\Models\Customer;
use Tests\TestCase;
class ResponseTest extends TestCase
{
protected $customer;
public function setUp(): void
{
parent::setUp();
$this->customer = Customer::factory()->enabled()->create();
}
public function testJson(): void
{
$responseData = (object) ['code' => 'NOT OK'];
// Test its response
$this->assertEquals('OK', $responseData->code, 'response data did not respond OK');
}
}
But instead of giving me the message "response data did not respond OK" it responds with "Target class [request] does not exist".
The relevant part of the factory look like this:
public function enabled()
{
return $this->state(function (array $attributes) {
return [
'enabled' => 1
];
});
}
The relevant part of the Customer
Model:
public static function boot()
{
parent::boot();
$request = request();
}
Oddly enough: when I don't use the state "enabled()" the problem does not occure. What am I doing wrong.
答案1
得分: 0
你的问题相当明显,你在boot
函数中使用了request
,但请求并不总是可用的。
正如另一位用户所指出的,绝不要将特定上下文引入到广泛的系统中,比如一个模型。你完全可以在CLI或Job/Listener上下文中使用模型,这样就不会有request
可用的情况...
而且你只是在做$request = request();
,这根本没有任何作用。删除整个boot
函数,你根本不需要它(至少在你分享的上下文/代码中不需要)。
英文:
Well, your issue is fairly obvious, you have request
inside the boot
function, when a request is not always available.
As another user stated, NEVER involve contexts that are specific, into broad systems, like a model. You can definitely use a model in a CLI or Job/Listener context, so you do not or could not have a request
available...
And you are also just doing $request = request();
, that does absolutely nothing. Delete the whole boot
function, you do not need it at all (at least in the context/code you shared)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论