PHPUnit : memcache_connect not working in PHPunit test case

标签 php memcached phpunit

注意:所有代码在没有 phpunit 的情况下都可以正常工作

文件 1:common.php:

  public function setNIMUID( $NIMUID ) { 

        if(is_bool(Cache::get("$NIMUID"))) {                
                $user_Array=array("_JID"=>(string)$NIMUID);
                Cache::set("$NIMUID",$user_Array);
        } 
       $this->NIMUID=(string)$NIMUID ;
    }

文件2:memcache.class.php
方法一:

   protected function __construct(array $servers) {  
    if(!$servers) {
        trigger_error('No memcache servers to connect', E_USER_WARNING);
    }
    for($i = 0, $n = count($servers); $i<$n; ++ $i) {
        ($con = memcache_connect(key($servers[$i]), current($servers[$i])))&&$this->mc_servers[] = $con; 
    }
    $this->mc_servers_count = count($this->mc_servers);
    if(!$this->mc_servers_count) {
        $this->mc_servers[0] = null;
    }
}

方法2:

      static function get($key) {
      return self::singleton()->getMemcacheLink($key)->get($key);
      } 

方法3:

static function singleton() {
    //Write here where from to get the servers list from, like 
    global $memcache_servers;

    self::$instance||self::$instance = new Cache($memcache_servers);
    return self::$instance;
}

文件 3:commonTest.php

public function testCommon()
      { 
      $Common = new Common();
      $Common->setNIMUID("saurabh4"); 
      }

$memcache_servers 变量:

 $memcache_servers = array(
    array('localhost'=>'11211'),
    array('127.0.0.1'=>'11211')
    );

错误:

Fatal error: Call to undefined function memcache_connect()

最佳答案

单元测试应该是可重复的、快速的和隔离的。这意味着您不应该连接到外部服务来对您的类进行单元测试。 如果您想测试 Common 是否正常工作,您应该测试它的行为,在本例中是按照您的预期调用 Cache 类。

为此,you'll need to use mocks 。使用模拟,您可以设置一些期望,例如将以特定方式调用该对象。如果您的类按预期被称为 memcached 类,您可以假设您的功能工作正常。你怎么知道 Cache 类工作正常?因为 Cache 类有自己的单元测试。

为了使用模拟(或 stub ),您需要更改编程方式并避免像 Cache::set() 中那样的静态调用。相反,您应该使用类实例和普通调用。如何?将 Cache 实例传递给您的 Common 类。这个概念叫做Dependency injection 。您的通用代码如下所示:

public function __construct( $cache ) {
    $this->cache = $cache;
}

public function setNIMUID( $NIMUID ) { 

    if(is_bool($this->cache->get("$NIMUID"))) {                
            $user_Array=array("_JID"=>(string)$NIMUID);
            $this->cache->set("$NIMUID",$user_Array);
    } 
   $this->NIMUID=(string)$NIMUID ;
}

关于PHPUnit : memcache_connect not working in PHPunit test case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17405092/

相关文章:

PHP Composer 自动加载需要永远

php - 从我的数据库获取个人资料图片以显示在 php 页面上

PHP 在生成文档时在服务器上创建文档副本

PHP换行符似乎不起作用

memcached - memcached 能否充分利用多核?

symfony - PHPUnit LogicException : The request was not redirected. Symfony

php - WebTestCase 中的空 cookies jar

PHPUnit 找不到我的测试文件或直接执行它们

python - 分离的 SQLalchemy session 无法延迟加载 backref 对象

python - 如何在django项目中使用memcached?