LoggerAwareTraitTest   A
last analyzed

Complexity

Total Complexity 2

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 45
rs 10
c 0
b 0
f 0
wmc 2
lcom 1
cbo 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A buildMock() 0 8 1
A testSetAndGet() 0 29 1
1
<?php
2
namespace FwlibTest\Cache;
3
4
use Fwlib\Cache\Logger;
5
use Fwlib\Cache\LoggerAwareTrait;
6
use Fwlib\Cache\LoggerInterface;
7
use Fwlib\Cache\OperateType;
8
use Fwolf\Wrapper\PHPUnit\PHPUnitTestCase;
9
use PHPUnit_Framework_MockObject_MockObject as MockObject;
10
11
/**
12
 * @copyright   Copyright 2015 Fwolf
13
 * @license     http://www.gnu.org/licenses/lgpl.html LGPL-3.0+
14
 */
15
class LoggerAwareTraitTest extends PHPUnitTestCase
16
{
17
    /**
18
     * @return MockObject | LoggerAwareTrait
19
     */
20
    protected function buildMock()
21
    {
22
        $mock = $this->getMockBuilder(LoggerAwareTrait::class)
23
            ->setMethods(null)
24
            ->getMockForTrait();
25
26
        return $mock;
27
    }
28
29
30
    public function testSetAndGet()
31
    {
32
        /** @var MockObject|LoggerInterface $logger */
33
        $logger = $this->getMock(Logger::class, ['log']);
34
        $logger->expects($this->once())
0 ignored issues
show
Bug introduced by
The method expects does only exist in PHPUnit_Framework_MockObject_MockObject, but not in Fwlib\Cache\LoggerInterface.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
35
            ->method('log');
36
37
        $loggerAware = $this->buildMock();
38
39
        // Before logger instance set
40
        $this->reflectionCall(
41
            $loggerAware,
42
            'log',
43
            [OperateType::GET, 'dummy', 'true']
44
        );
45
46
        // After logger instance set
47
        $loggerAware->setLogger($logger);
48
        $this->reflectionCall(
49
            $loggerAware,
50
            'log',
51
            [OperateType::GET, 'dummy', 'true']
52
        );
53
54
        $this->assertInstanceOf(
55
            LoggerInterface::class,
56
            $loggerAware->getLogger()
57
        );
58
    }
59
}
60