LoginSignup
6
7

More than 5 years have passed since last update.

PHPUnitでコンストラクタを呼ばずにテストする

Last updated at Posted at 2013-02-12

テスト対象コード

SampleClass.php
<?php

class SampleClass
{
    public function __construct()
    {
        exit;
    }

    public function hoge()
    {
        return TRUE;
    }
}
  • hoge()がTRUEを返すことを検証したい

テストコード

SampleClassTest.php
<?php

require_once 'SampleClass.php';

class SampleClassTest extends PHPUnit_Framework_TestCase
{
    public function testHogeReturnTrue()
    {
        $this->class = new SampleClass();
        $this->assertTrue($this->class->hoge());
    }
}

テスト実行結果

$ phpunit SampleClassTest.php 
PHPUnit 3.6.10 by Sebastian Bergmann.
  • コンストラクタが呼ばれexitが実行されるために検証結果が得られない

テストコード

SampleClassTest.php
<?php

require_once 'SampleClass.php';

class SampleClassTest extends PHPUnit_Framework_TestCase
{
    public function testHogeReturnTrue()
    {
        $class = $this->getMockBuilder('SampleClass')
                      ->setMethods(NULL)
                      ->disableOriginalConstructor()
                      ->getMock();

        $this->assertTrue($class->hoge());
    }
}

テスト実行結果

$ phpunit SampleClassTest.php
PHPUnit 3.6.10 by Sebastian Bergmann.

.

Time: 0 seconds, Memory: 2.75Mb

OK (1 test, 1 assertion)
  • MockBuilderを活用しdisableOriginalConstructor()を設定することで検証結果を得ることができた
6
7
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
6
7