sebastianbergmann / phpunit

The PHP Unit Testing framework.
https://phpunit.de/
BSD 3-Clause "New" or "Revised" License
19.66k stars 2.2k forks source link

Generating a mock from an abstract class results in NULL(sort of) #2947

Closed robertmain closed 6 years ago

robertmain commented 6 years ago
Q A
PHPUnit version 6.5.5
PHP version 7.1.9
Installation Method Composer

Issue

I am attempting to generate a mock of an abstract class, but getMockForAbstractClass() is returning NULL. I can't find anything in the documentation to point to where I'm going wrong, but calling $this->adapter->get() raises Error: Call to a member function get() on null

var_dump($this->adapter) gets me this:

class Mock_Adapter_229a80cc#21 (3) {
  private $__phpunit_invocationMocker =>
  NULL
  private $__phpunit_originalObject =>
  NULL
  private $__phpunit_configurable =>
  array(2) {
    [0] =>
    string(3) "get"
    [1] =>
    string(3) "set"
  }
}

Code

Unit Under Test

<?php

namespace UniformCache;

use UniformCache\CacheItem;

abstract class Adapter
{
    public function construct()
    {
        $this->createCacheItem = \Closure::bind(
            function ($key, $value, $isHit) {
                $item        = new CacheItem();
                $item->key   = $key;
                $item->value = $value;
                $item->isHit = $isHit;
                return $item;
            },
            null,
            CacheItem::class
        );
    }

    /**
     * Retrieve one (ore more) items from the cache backend
     *
     * @param array $item_ids An array of one or more item ids to retreive from the cache
     *
     * @return CacheItem[] An array of `CacheItem` objects for the requested values. `CacheItem` objects will still
     * be returned even in the event of a cache miss.
     */
    abstract public function get(array $item_ids):array;

    /**
     * Store an item in the cache
     *
     * @param mixed $key   The key under which `$value` should be stored
     * @param mixed $value The value to store in the cache. This should be a PHP serializeable value
     *
     * @return void
     */
    abstract public function set(mixed $key, mixed $value):void;
}

Test

<?php

use PHPUnit\Framework\TestCase;

use UniformCache\Cache;
use UniformCache\CacheItem;
use UniformCache\Adapter;

/**
 * CacheItemPool
 *
 */
class CacheItemPool extends TestCase
{

    public $adapter = null;

    public function setUp()
    {
        $this->adapter = $this->getMockBuilder(Adapter::class)
                              ->enableOriginalConstructor()
                              ->getMockForAbstractClass();
    }

    /**
     * @test
     */
    public function returns_a_cache_item_representing_the_specified_key()
    {
        $this->adapter->method('get')
                      ->willReturnCallback(function () {
                          $cacheItem = $this->createCacheItem('my_key', 'my_item', true);
                          return [$cacheItem];
                      });

        $cache     = new Cache([$this->adapter]);
        $cacheItem = $cache->getItem('my_key');

        $this->assertInstanceOf(CacheItem, $cacheItem);
        $this->assertEquals('my_value', $cacheItem->get());
        $this->assertEquals('my_key', $cacheItem->getKey());
    }
}

Composer Info

cilex/cilex                         1.1.0   The PHP micro-framework for Command line tools based on the Symfony2 Components
cilex/console-service-provider      1.0.0   Console Service Provider
container-interop/container-interop 1.2.0   Promoting the interoperability of container objects (DIC, SL, etc.)
doctrine/annotations                v1.6.0  Docblock Annotations Parser
doctrine/instantiator               1.1.0   A small, lightweight utility to instantiate objects in PHP without invoking their constructors
doctrine/lexer                      v1.0.1  Base library for a lexer that can be used in Top-Down, Recursive Descent Parsers.
erusev/parsedown                    1.6.4   Parser for Markdown.
herrera-io/json                     1.0.3   A library for simplifying JSON linting and validation.
herrera-io/phar-update              1.0.3   A library for self-updating Phars.
jms/metadata                        1.6.0   Class/method/property metadata management in PHP
jms/parser-lib                      1.0.0   A library for easily creating recursive-descent parsers.
jms/serializer                      1.10.0  Library for (de-)serializing data of any complexity; supports XML, JSON, and YAML.
justinrainbow/json-schema           1.6.1   A library to validate a json schema.
kherge/version                      1.0.1   A parsing and comparison library for semantic versioning.
limedeck/phpunit-detailed-printer   3.1.1   Formatter for the detailed output of PHPUnit tests.
monolog/monolog                     1.23.0  Sends your logs to files, sockets, inboxes, databases and various web services
myclabs/deep-copy                   1.7.0   Create deep copies (clones) of your objects
nikic/php-parser                    v1.4.1  A PHP parser written in PHP
phar-io/manifest                    1.0.1   Component for reading phar.io manifest information from a PHP Archive (PHAR)
phar-io/version                     1.0.1   Library for handling version information and constraints
phpcollection/phpcollection         0.5.0   General-Purpose Collection Library for PHP
phpdocumentor/fileset               1.0.0   Fileset component for collecting a set of files given directories and file paths
phpdocumentor/graphviz              1.0.4   
phpdocumentor/phpdocumentor         v2.9.0  Documentation Generator for PHP
phpdocumentor/reflection            3.0.1   Reflection library to do Static Analysis for PHP Projects
phpdocumentor/reflection-docblock   2.0.5   
phpoption/phpoption                 1.5.0   Option Type for PHP
phpspec/prophecy                    1.7.3   Highly opinionated mocking framework for PHP 5.3+
phpunit/php-code-coverage           5.3.0   Library that provides collection, processing, and rendering functionality for PHP code coverage information.
phpunit/php-file-iterator           1.4.5   FilterIterator implementation that filters files based on a list of suffixes.
phpunit/php-text-template           1.2.1   Simple template engine.
phpunit/php-timer                   1.0.9   Utility class for timing
phpunit/php-token-stream            2.0.2   Wrapper around PHP's tokenizer extension.
phpunit/phpunit                     6.5.5   The PHP Unit Testing framework.
phpunit/phpunit-mock-objects        5.0.5   Mock Object library for PHPUnit
pimple/pimple                       v1.1.1  Pimple is a simple Dependency Injection Container for PHP 5.3
psr/cache                           1.0.1   Common interface for caching libraries
psr/container                       1.0.0   Common Container Interface (PHP FIG PSR-11)
psr/log                             1.0.2   Common interface for logging libraries
sebastian/code-unit-reverse-lookup  1.0.1   Looks up which function or method a line of code belongs to
sebastian/comparator                2.1.1   Provides the functionality to compare PHP values for equality
sebastian/diff                      2.0.1   Diff implementation
sebastian/environment               3.1.0   Provides functionality to handle HHVM/PHP environments
sebastian/exporter                  3.1.0   Provides the functionality to export PHP variables for visualization
sebastian/global-state              2.0.0   Snapshotting of global state
sebastian/object-enumerator         3.0.3   Traverses array structures and object graphs to enumerate all referenced objects
sebastian/object-reflector          1.1.1   Allows reflection of object attributes, including inherited and non-public ones
sebastian/recursion-context         3.0.0   Provides functionality to recursively process PHP variables
sebastian/resource-operations       1.0.0   Provides a list of PHP built-in functions that operate on resources
sebastian/version                   2.0.1   Library that helps with managing the version number of Git-hosted PHP projects
seld/jsonlint                       1.6.2   JSON Linter
simplon/mysql                       0.3.2   Simplon MySQL Library
squizlabs/php_codesniffer           3.2.2   PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined set of coding standards.
symfony/config                      v2.8.32 Symfony Config Component
symfony/console                     v2.8.32 Symfony Console Component
symfony/debug                       v3.0.9  Symfony Debug Component
symfony/event-dispatcher            v2.8.32 Symfony EventDispatcher Component
symfony/filesystem                  v3.0.9  Symfony Filesystem Component
symfony/finder                      v2.8.32 Symfony Finder Component
symfony/polyfill-mbstring           v1.6.0  Symfony polyfill for the Mbstring extension
symfony/process                     v2.8.32 Symfony Process Component
symfony/stopwatch                   v2.8.32 Symfony Stopwatch Component
symfony/translation                 v3.0.9  Symfony Translation Component
symfony/validator                   v2.8.32 Symfony Validator Component
theseer/tokenizer                   1.1.0   A small library for converting tokenized PHP source code into XML and potentially other formats
twig/twig                           v1.35.0 Twig, the flexible, fast, and secure template language for PHP
zendframework/zend-cache            2.7.2   provides a generic way to cache any data
zendframework/zend-config           2.6.0   provides a nested object property based user interface for accessing this configuration data within application code
zendframework/zend-eventmanager     3.2.0   Trigger and listen to events within a PHP application
zendframework/zend-filter           2.7.2   provides a set of commonly needed data filters
zendframework/zend-hydrator         1.1.0   
zendframework/zend-i18n             2.7.4   
zendframework/zend-json             3.0.0   provides convenience methods for serializing native PHP to JSON and decoding JSON to native PHP
zendframework/zend-serializer       2.8.1   provides an adapter based interface to simply generate storable representation of PHP types by different facilities, and recover
zendframework/zend-servicemanager   2.7.10  
zendframework/zend-stdlib           2.7.7   
zetacomponents/base                 1.9.1   The Base package provides the basic infrastructure that all packages rely on. Therefore every component relies on this package.
zetacomponents/document             1.3.1   The Document components provides a general conversion framework for different semantic document markup languages like XHTML, Docboo...
robertmain commented 6 years ago

Turns out I'd written public function construct instead of public function __construct. Thus the constructor was never being called and was therefore never setting the adapter as the class property.

/headdesk