Completed
Push — master ( 886d08...3c4a95 )
by Kenji
03:47 queued 01:20
created

CIPHPUnitTestDouble::getDouble()   C

Complexity

Conditions 12
Paths 72

Size

Total Lines 58

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
nc 72
nop 3
dl 0
loc 58
rs 6.4896
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Part of ci-phpunit-test
4
 *
5
 * @author     Kenji Suzuki <https://github.com/kenjis>
6
 * @license    MIT License
7
 * @copyright  2015 Kenji Suzuki
8
 * @link       https://github.com/kenjis/ci-phpunit-test
9
 */
10
11
class CIPHPUnitTestDouble
12
{
13
	protected $testCase;
14
15
	public function __construct(PHPUnit_Framework_TestCase $testCase)
16
	{
17
		$this->testCase = $testCase;
18
	}
19
20
	/**
21
	 * Get Mock Object
22
	 *
23
	 * $email = $this->getMockBuilder('CI_Email')
24
	 *	->disableOriginalConstructor()
25
	 *	->setMethods(['send'])
26
	 *	->getMock();
27
	 * $email->method('send')->willReturn(TRUE);
28
	 *
29
	 *  will be
30
	 *
31
	 * $email = $this->getDouble('CI_Email', ['send' => TRUE]);
32
	 *
33
	 * @param  string $classname
34
	 * @param  array  $params             [method_name => return_value]
35
	 * @param  mixed  $constructor_params false: disable constructor, array: constructor params
36
	 *
37
	 * @return mixed PHPUnit mock object
38
	 */
39
	public function getDouble($classname, $params, $constructor_params = false)
40
	{
41
		// `disableOriginalConstructor()` is the default, because if we call
42
		// constructor, it may call `$this->load->...` or other CodeIgniter
43
		// methods in it. But we can't use them in
44
		// `$this->request->setCallablePreConstructor()`
45
		$mockBuilder = $this->testCase->getMockBuilder($classname);
46
		if ($constructor_params === false)
47
		{
48
			$mockBuilder->disableOriginalConstructor();
49
		}
50
		elseif (is_array($constructor_params))
51
		{
52
			$mockBuilder->setConstructorArgs($constructor_params);
53
		}
54
55
		$methods = [];
56
		$onConsecutiveCalls = [];
57
		$otherCalls = [];
58
59
		foreach ($params as $key => $val) {
60
			if (is_int($key)) {
61
				$onConsecutiveCalls = array_merge($onConsecutiveCalls, $val);
62
				$methods[] = array_keys($val)[0];
63
			} else {
64
				$otherCalls[$key] = $val;
65
				$methods[] = $key;
66
			}
67
		}
68
69
		$mock = $mockBuilder->setMethods($methods)->getMock();
70
71
		foreach ($onConsecutiveCalls as $method => $returns) {
72
			$mock->expects($this->testCase->any())->method($method)
73
				->will(
74
					call_user_func_array(
75
						[$this->testCase, 'onConsecutiveCalls'],
76
						$returns
77
					)
78
				);
79
		}
80
81
		foreach ($otherCalls as $method => $return)
82
		{
83
			if (is_object($return) && ($return instanceof PHPUnit_Framework_MockObject_Stub || $return instanceof PHPUnit\Framework\MockObject\Stub)) {
0 ignored issues
show
Bug introduced by
The class PHPUnit_Framework_MockObject_Stub does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
Bug introduced by
The class PHPUnit\Framework\MockObject\Stub does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
84
				$mock->expects($this->testCase->any())->method($method)
85
					->will($return);
86
			} elseif (is_object($return) && $return instanceof Closure) {
87
				$mock->expects($this->testCase->any())->method($method)
88
					->willReturnCallback($return);
89
			} else {
90
				$mock->expects($this->testCase->any())->method($method)
91
					->willReturn($return);
92
			}
93
		}
94
95
		return $mock;
96
	}
97
98
	protected function _verify($mock, $method, $params = null, $expects, $with)
99
	{
100
		$invocation = $mock->expects($expects)
101
			->method($method);
102
103
		if ($params === null) {
104
			return;
105
		}
106
107
		call_user_func_array([$invocation, $with], $params);
108
	}
109
110
	/**
111
	 * Verifies that method was called exactly $times times
112
	 *
113
	 * $loader->expects($this->exactly(2))
114
	 * 	->method('view')
115
	 * 	->withConsecutive(
116
	 *		['shop_confirm', $this->anything(), TRUE],
117
	 * 		['shop_tmpl_checkout', $this->anything()]
118
	 * 	);
119
	 *
120
	 *  will be
121
	 *
122
	 * $this->verifyInvokedMultipleTimes(
123
	 * 	$loader,
124
	 * 	'view',
125
	 * 	2,
126
	 * 	[
127
	 * 		['shop_confirm', $this->anything(), TRUE],
128
	 * 		['shop_tmpl_checkout', $this->anything()]
129
	 * 	]
130
	 * );
131
	 *
132
	 * @param mixed  $mock   PHPUnit mock object
133
	 * @param string $method
134
	 * @param int    $times
135
	 * @param array  $params arguments
136
	 */
137
	public function verifyInvokedMultipleTimes($mock, $method, $times, $params = null)
138
	{
139
		$this->_verify(
140
			$mock, $method, $params, $this->testCase->exactly($times), 'withConsecutive'
141
		);
142
	}
143
144
	/**
145
	 * Verifies a method was invoked at least once
146
	 *
147
	 * @param mixed  $mock   PHPUnit mock object
148
	 * @param string $method
149
	 * @param array  $params arguments
150
	 */
151
	public function verifyInvoked($mock, $method, $params = null)
152
	{
153
		$this->_verify(
154
			$mock, $method, $params, $this->testCase->atLeastOnce(), 'with'
155
		);
156
	}
157
158
	/**
159
	 * Verifies that method was invoked only once
160
	 *
161
	 * @param mixed  $mock   PHPUnit mock object
162
	 * @param string $method
163
	 * @param array  $params arguments
164
	 */
165
	public function verifyInvokedOnce($mock, $method, $params = null)
166
	{
167
		$this->_verify(
168
			$mock, $method, $params, $this->testCase->once(), 'with'
169
		);
170
	}
171
172
	/**
173
	 * Verifies that method was not called
174
	 *
175
	 * @param mixed  $mock   PHPUnit mock object
176
	 * @param string $method
177
	 * @param array  $params arguments
178
	 */
179
	public function verifyNeverInvoked($mock, $method, $params = null)
180
	{
181
		$this->_verify(
182
			$mock, $method, $params, $this->testCase->never(), 'with'
183
		);
184
	}
185
}
186