Reputation: 35963
I'm trying to test a simple function inside my service in Symfony.
The function get the post value if exist and set a multidimensional array. this is my function inside a service:
public function setValue(Request $request)
{
for($i = 1; $i <= 3; $i++){
for($j = 1; $j <= 3; $j++){
if(($request->request->get('cell_' . $i . '_' . $j) != null){
$value = $request->request->get('cell_' . $i . '_' . $j);
echo('Value: ' . $value . '|');
$this->tiles[$i][$j] = $value;
}
else{
$this->tiles[$i][$j] = '0';
}
}
}
}
And this is my part of test (not all test but a simple part)
public function testGetSatusGameEnd()
{
$this->requestMock = $this
->getMockBuilder('Symfony\Component\HttpFoundation\Request')
->disableOriginalConstructor()
->getMock();
$this->requestMock->request = $this
->getMockBuilder('Symfony\Component\HttpFoundation\ParameterBag')
->disableOriginalConstructor()
->getMock();
$this->requestMock->request->expects($this->at(0))
->method('get')
->with('cell_1_1')
->will($this->returnValue('1'));
$board = new Board();
$board->setValue($this->requestMock);
var_dump($board->getArrayResult());
}
In this case I set only a cell in theory with value 1 but when I dump all the result I get this
array(3) {
[1] =>
array(3) {
[1] =>
NULL
[2] =>
string(1) "0"
[3] =>
string(1) "0"
}
[2] =>
array(3) {
[1] =>
string(1) "0"
[2] =>
string(1) "0"
[3] =>
string(1) "0"
}
[3] =>
array(3) {
[1] =>
string(1) "0"
[2] =>
string(1) "0"
[3] =>
string(1) "0"
}
}
Because inside cell_1_1
there is an empty value I check, but I'm expected to have 1
not empty!
How can I return 1
inside cell_1_1
, What is the error of my mock?
Thanks
Upvotes: 1
Views: 116
Reputation: 3483
The reason get
is returning null is because the index for at()
has already been incremented by the first call (in the if statement).
I found some useful information on this article about it being misleading.
You might not want to bother with expects()
and at()
at all, since it doesn't really reflect the behaviour of an actual parameter bag, which would return the same regardless of when it was called.
You could use the mock objects with a callback to return '1' only when the name is cell_1_1, like this:
$this
->requestMock
->request
->method('get')
->will($this->returnCallback(function ($name) {
return $name === 'cell_1_1' ? '1' : null;
}));
Or you could just use the Symfony request itself and same yourself a lot of complication :-)
Sample code for test using real Request:
$request = new Request([], ['cell_1_1' => '1']);
$board = new Board();
$board->setValue($request);
Upvotes: 1
Reputation: 2549
You are not filling index 0
of the array.
Take a look at your loops:
...
for($i = 1; $i <= 3; $i++){
for($j = 1; $j <= 3; $j++){
...
Both start from index 1
instead of index 0
. That way the first array-element won't never be set and that is why it is null
.
You have to change your for
this way.
for($i = 0; $i < 3; $i++){
for($j = 0; $j < 3; $j++){
Upvotes: 0