UtilMockSwitcherTraitTest::buildMock()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
namespace FwlibTest\Test;
3
4
use Fwlib\Test\UtilMockSwitcherTrait;
5
use Fwlib\Util\Common\StringUtil;
6
use Fwlib\Util\UtilContainer;
7
use Fwolf\Wrapper\PHPUnit\PHPUnitTestCase;
8
use PHPUnit_Framework_MockObject_MockObject as MockObject;
9
10
/**
11
 * @copyright   Copyright 2015 Fwolf
12
 * @license     http://www.gnu.org/licenses/lgpl.html LGPL-3.0+
13
 */
14
class UtilMockSwitcherTraitTest extends PHPUnitTestCase
15
{
16
    use UtilMockSwitcherTrait;
17
18
19
    /**
20
     * @param   string[] $methods
21
     * @return  MockObject
22
     */
23
    protected function buildMock(array $methods = null)
24
    {
25
        $mock = $this->getMockBuilder(UtilMockSwitcherTrait::class)
26
            ->setMethods($methods)
27
            ->getMockForTrait();
28
29
        return $mock;
30
    }
31
32
33
    public function testBeginAndEnd()
34
    {
35
        $this->assertEquals(
36
            'any',
37
            UtilContainer::getInstance()->getString()->toCamelCase('any')
38
        );
39
40
41
        /** @var MockObject|StringUtil $stringUtil */
42
        $stringUtil = $this->beginUtilMock('String', ['toCamelCase']);
43
        $stringUtil->expects($this->any())
0 ignored issues
show
Bug introduced by
The method expects does only exist in PHPUnit_Framework_MockObject_MockObject, but not in Fwlib\Util\Common\StringUtil.

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...
44
            ->method('toCamelCase')
45
            ->willReturn('fooBar');
46
47
        $this->assertEquals(
48
            'fooBar',
49
            UtilContainer::getInstance()->getString()->toCamelCase('any')
50
        );
51
52
53
        $this->endUtilMock('String');
54
        $this->assertEquals(
55
            'any',
56
            UtilContainer::getInstance()->getString()->toCamelCase('any')
57
        );
58
    }
59
}
60