测试私有方法不起作用 [英] Testing Private Methods Not Working

查看:86
本文介绍了测试私有方法不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的测试班;

<?php
namespace stats\Test;

use stats\Baseball;

class BaseballTest extends \PHPUnit_Framework_TestCase
{

  public function setUp() {
    $this->instance = new Baseball();
  }

  public function tearDown() {
    unset($this->instance);
  }

  public function testOps() {
    $obp = .363;
    $slg = .469;
    $ops = $this->instance->calc_ops($obp, $slg); //line 23

    $expectedops = $obp + $slg;

    $this->assertEquals($expectedops, $ops);
  }

}

这是我的棒球课;

<?php
namespace stats;

class Baseball
{
  private function calc_ops($slg,$obp)
  {
   return $slg + $obp;
  }
}

运行测试时,我不断收到此错误;

And I keep getting this error when I run my tests;

Fatal error: Call to private method stats\Baseball::calc_ops() from context 'stats\Test\BaseballTest' in /media/sf_sandbox/phpunit/stats/Test/BaseballTest.php on line 23

这只是我正在遵循的教程.但是它无法正常工作,因此令人沮丧,因为我正在严格遵循它.

This is only a tutorial I am following.. But it's not working so it's frustrating because I am following it exactly.

推荐答案

您无法测试私有方法,可以使用变通方法,并如本

You can't test private method, you can use a workaround and invoke it via reflection as described in this article.

这是基于以下文章的有效示例:

This is a working example based on the article:

class BaseballTest extends \PHPUnit_Framework_TestCase
{

    public function setUp() {
        $this->instance = new Baseball();
    }

    public function tearDown() {
        unset($this->instance);
    }

    public function testOps() {
        $obp = .363;
        $slg = .469;
//        $ops = $this->instance->calc_ops($obp, $slg); //line 23
        $ops = $this->invokeMethod($this->instance, 'calc_ops', array($obp, $slg));

        $expectedops = $obp + $slg;

        $this->assertEquals($expectedops, $ops);
    }

    /**
     * Call protected/private method of a class.
     *
     * @param object &$object    Instantiated object that we will run method on.
     * @param string $methodName Method name to call
     * @param array  $parameters Array of parameters to pass into method.
     *
     * @return mixed Method return.
     */
    public function invokeMethod(&$object, $methodName, array $parameters = array())
    {
        $reflection = new \ReflectionClass(get_class($object));
        $method = $reflection->getMethod($methodName);
        $method->setAccessible(true);

        return $method->invokeArgs($object, $parameters);
    }

这篇关于测试私有方法不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆