Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Unit Testing Laravel

nunulk
November 14, 2018

Unit Testing Laravel

nunulk

November 14, 2018
Tweet

More Decks by nunulk

Other Decks in Programming

Transcript

  1. Ϣχοτςετͷྫʢܭࢉʣ // test public function testRemainingHousrs() { $today = Carbon::today();

    $task = factory(Task::class)->make([ 'due' => Carbon::tomorrow() ]); $this->assertSame(24, $task->remainingHours($today)); } // production public function remainingHours(Carbon $datetime): int { return $this->due->diffInHours($datetime); }
  2. Ϣχοτςετͷྫʢ৚݅൑ఆʣ // test public function testIsOverdue() { $now = Carbon::now();

    $task = factory(Task::class)->make([ 'due' => Carbon::yesterday() ]); $this->assertTrue($task->isOverdue($now)); } // production public function isOverdue(Carbon $datetime): bool { return $this->due->lessThan($datetime); }
  3. PHPUnit w ΞαʔγϣϯBTTFSU&RVBMT BTTFSU4BNF BTTFSU5SVF  BTTFSU'BMTF BTTFSU$POUBJOT BTTFSU/VMM BTTFSU5IBU

    FUD w Ξϊςʔγϣϯ!EBUB1SPWJEFS !FYQFDUFE&YDFQUJPO  !HSPVQ FUD w ίʔυΧόϨοδ
  4. PHPUnit in Laravel w .PDLFSZ 'BLFSΛόϯυϧ w .PEFM'BDUPSZ 'BLFS w

    'BDBEF .PDLFSZ w %*ίϯςφΛ࢖ͬͨ.PDLJOH w ศརτϨΠτ *OUFSBDUT8JUI"VUIFOUJDBUJPO  .PDLT"QQMJDBUJPO4FSWJDFT  *OUFSBDUT8JUI%BUBCBTF3FGSFTI%BUBCBTF  %BUBCBTF5SBOTBDUJPOT FUD
  5. Mockery $task = factory(Task::class)
 ->states(['doing', 'high'])
 ->create(); Mockery::mock(TaskRepository::class) ->shouldReceive('find')
 ->once()


    ->andReturn($task); Mockery::mock(Log::class) ->shouldReceive(‘debug')
 ->once() ->andReturnUsing(function ($subject, $body) { // ͜ͷதͰΞαʔγϣϯ͕Ͱ͖·͢ $this->assertContains('Laravel', $body); });
  6. Model Factory, Faker $factory->define(Task::class, function (Faker $faker) { return [

    'subject' => $faker->sentence, 'priority' => Priority::default(), 'status' => Status::default(), ]; }); $factory->state(Task::class, 'doing', function () { return [ 'status' => Status::DOING(), ]; }); factory(Task::class)->states(['doing', 'high'])->create();