LoginSignup
12
14

More than 5 years have passed since last update.

PHPUnitで関数が呼び出されたことをテストする

Last updated at Posted at 2013-03-11

テスト対象コード

Sample.php
<?php

class Sample
{
    public function error()
    {
        $this->redirect();
    }

    public function redirect()
    {
        header("Location: http://github.com/");
    }
}
  • error() は redirect() を呼び出すことを検証したい

テストコード

SampleTest.php
<?php

require_once 'Sample.php';

class SampleTest extends PHPUnit_Framework_TestCase
{
    public function testCallRedirectWhenError()
    {
        $sample = $this->getMockBuilder('Sample')
                       ->setMethods(array('redirect'))
                       ->getMock();
        $sample->expects($this->once())->method('redirect');

        $sample->error();
    }
}

テスト実行結果

$ phpunit SampleClassTest.php 
PHPUnit 3.7.13 by Sebastian Bergmann.

.

Time: 0 seconds, Memory: 3.50Mb

OK (1 test, 1 assertion)
  • redirect()のheader()を無害化しつつredirect()の呼び出しについての検証結果を得ることができた
12
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
14