我在类上有一个> [1,3,4].map(x=>5) // (3) [5, 5, 5]
> Array(3).map(x=>5) // (3) [empty × 3]
方法,这只是generate()
类实例的一种简便方法。它接受create
,该类型在方法上提示。我正在尝试对此进行单元测试,而我知道的唯一方法是request
和make
并通过它。这不起作用,因为它不是answer
。有没有解决的办法?方法如下:
request
这是测试
public static function generate(Question $question, Request $request): self
{
return self::create([
'user_id' => Auth::user()->getKey(),
'question_id' => $question->getKey(),
'answer_body' => $request->answer_body,
]);
}
测试通过,直到我在方法中键入提示/** @test */
public function it_can_generate_a_new_instance()
{
$user = factory(User::class)->create();
$this->actingAs($user);
$question = factory(Question::class)->create();
$answer = factory(Answer::class)->make();
Answer::generate($question, $answer);
$this->assertEquals($user->getKey(), Answer::first()->user_id);
$this->assertEquals($question->getKey(), Answer::first()->question_id);
$this->assertEquals($answer->answer_body, Answer::first()->answer_body);
}
。
答案 0 :(得分:1)
您可以使用给定的属性创建一个新的请求对象。可能有点脆弱,但应该可以使用:
public function it_can_generate_a_new_instance()
{
$user = factory(User::class)->create();
$this->actingAs($user);
$question = factory(Question::class)->create();
$answer = factory(Answer::class)->make();
$request = new Request([ 'answer_body' => $answer->answer_body ]);
Answer::generate($question, $request);
$this->assertEquals($user->getKey(), Answer::first()->user_id);
$this->assertEquals($question->getKey(), Answer::first()->question_id);
$this->assertEquals($answer->answer_body, Answer::first()->answer_body);
}
答案 1 :(得分:0)
请求仅应存在于控制器上,而不应存在于模型Answer
中(否则您将遇到类似^^的错误)
如果您的流程需要一个请求,那么您应该改为测试一个http请求:
/** @test */
public function it_can_generate_a_new_instance()
{
$user = factory(User::class)->create();
$this->actingAs($user);
$question = factory(Question::class)->create();
$answer = factory(Answer::class)->make();
$this->post(route('answer.store'), $answer->toArray());
// Then your answer will be generated in your controller
$this->assertEquals($user->getKey(), Answer::first()->user_id);
$this->assertEquals($question->getKey(), Answer::first()->question_id);
$this->assertEquals($answer->answer_body, Answer::first()->answer_body);
}