Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

テスト対象コード

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()の呼び出しについての検証結果を得ることができた
kseta
野球/PHP/Python/Selenium/Symfony/Agile渋谷/TDD/ 野球の助っ人はいつでも!!
http://kseta.hatenablog.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away