PHPUnit Strange behavior when mocking MongoCollection - php

Assume I have this test:
public function testStorage()
{
$collection = $this->getMockBuilder('MongoCollection')->disableOriginalConstructor()->getMock();
$collection->method('findOne')->will($this->returnValueMap([
[['_id' => 'aaa'], ['content'], 'ccc'],
]));
$this->assertEquals('ccc', $collection->findOne(['_id' => 'aaa'], ['content']));
}
When running unit test it says: Failed asserting that null matches expected 'ccc'.
I couldn't figure out why. But if I switch to mock another function, let's say: find it should work.
public function testStorage()
{
$collection = $this->getMockBuilder('MongoCollection')->disableOriginalConstructor()->getMock();
$collection->method('find')->will($this->returnValueMap([
[['_id' => 'aaa'], ['content'], 'ccc'],
]));
$this->assertEquals('ccc', $collection->find(['_id' => 'aaa'], ['content']));
}
OK (1 test, 1 assertion)
I really appreciate your help! Thank you very much!

I use getMock and it's work for me:
$collection = $this->getMock('MongoCollection', ['find', 'findOne'], [], '', false);
$collection->method('find')->will($this->returnValue([
[['_id' => 'aaa'], ['content'], 'ccc']
]));
$collection->method('findOne')->will($this->returnValue([
[['_id' => 'aaa'], ['content'], 'ccc']
]));

Related

Object of class could not be converted to int

I want to write phpunit test for save method at my repository. My repo code is:
public function saveCustomer(Custom $custom)
{
try
{
$custom->save();
return array(
'status' => true,
'customerId' => $custom->getId()
);
}
catch(\Exception $e)
{
return array(
'status' => false,
'customerId' => 0
);
}
}
I wrote this test:
public function testSaveNewUye()
{
$request = array(
'email' => 'www#www.com',
'phone' => '555 555 555',
'password' => '34636'
);
$repo = new CustomerRepository();
$result_actual = $this->$repo->saveCustomer($request);
$result_expected = array(
'status' => true,
'customerId' => \DB::table('custom')->select('id')->orderBy('id', 'DESC')->first() + 1
);
self::assertEquals($result_expected, $result_actual);
}
I got the error given below:
ErrorException: Object of class App\CustomerRepository could not be converted to int
Can you help me?
Problem is here:
$repo = new CustomerRepository();
$result_actual = $this->$repo->saveCustomer($request);
You are assigning and using variables not the same.
Try like this instead:
$this->repo = new CustomerRepository();
// ^------- assign to `$this`
$result_actual = $this->repo->saveCustomer($request);
// ^------- remove `$`
When doing $this->$repo-> PHP tries to convert the (object) $repo to a string $this->(object)-> which does not work.
Then you have a second error here:
\DB::table('custom')->select('id')->orderBy('id', 'DESC')->first() + 1
From the database you get an object (instanceof stdClass) which you cannot simply + 1.
The whole thing is probably something like
\DB::table('custom')->select('id')->orderBy('id', 'DESC')->first()->id + 1
(From the returned object, you want the property id.)

laravel Invalid JSON was returned from the route. Perhaps an exception was thrown?

This is my test for store function
/** #test */
public function storeTest()
{
$this->be($this->user);
$response = $this->json('POST', '/client/ocp/profile/247/route-', [
'name' => 'Test store',
'speed' => 4.5,
'created_by' => $this->user->id,
'client_id' => '262',
]);
$response
->seeStatusCode(302)
->seeJson(['status' => 'OK']);
}
when i run it i got this error
Invalid JSON was returned from the route. Perhaps an exception was thrown?
i try to add this header to solve a problem
['X-Requested-With' => 'XMLHttpRequest']
but it not solving
how i can solve this?

How do I deal with Class 'PHPUnit_Framework_TestCase' not found error?

I am trying to integrate to visa direct API. I decided to to it in PHP. However, as I am doing some tests from a sample code they have provided, I got stuck at Fatal error: Class 'PHPUnit_Framework_TestCase' not found error.
I have PHPUnit installed since when I check via phpunit --version ..I get PHPUnit 5.6.2 by Sebastian Bergmann and contributors.
Below is my code using PHPUnit, would someone direct me where my mistake is? Thank you.
<?php
class MVisaTest extends \PHPUnit_Framework_TestCase {
public function setUp() {
$this->visaAPIClient = new VisaAPIClient;
$strDate = date('Y-m-d\TH:i:s', time());
$this->mVisaTransactionRequest = json_encode ([
"acquirerCountryCode" => "643",
"acquiringBin" => "400171",
"amount" => "124.05",
"businessApplicationId" => "CI",
"cardAcceptor" => [
"address" => [
"city" => "Bangalore",
"country" => "IND"
],
"idCode" => "ID-Code123",
"name" => "Card Accpector ABC"
],
"localTransactionDateTime" => $strDate,
"merchantCategoryCode" => "4829",
"recipientPrimaryAccountNumber" => "4123640062698797",
"retrievalReferenceNumber" => "430000367618",
"senderAccountNumber" => "4541237895236",
"senderName" => "Mohammed Qasim",
"senderReference" => "1234",
"systemsTraceAuditNumber" => "313042",
"transactionCurrencyCode" => "USD",
"transactionIdentifier" => "381228649430015"
]);
}
public function testMVisaTransactions() {
$baseUrl = "visadirect/";
$resourcePath = "mvisa/v1/cashinpushpayments";
$statusCode = $this->visaAPIClient->doMutualAuthCall ( 'post', $baseUrl.$resourcePath, 'M Visa Transaction Test', $this->mVisaTransactionRequest );
$this->assertEquals($statusCode, "200");
}
}
You can just use TestCase class instead so you can say:
use PHPUnit\Framework\TestCase;
class MVisaTest extends TestCase {
// your tests goes here
}

Test every time is skipped by PHPUnit

I'm using PHPUnit with CakePHP to test a Custom Finder but test is every time skipped and I do not know what the reason
OK, but incomplete, skipped, or risky tests!
TestCase:
class UsersTableTest extends TestCase
{
public $fixtures = [
'app.users',
'app.user_types',
'app.bookings',
'app.stores'
];
public function setUp()
{
parent::setUp();
$this->Users = TableRegistry::get('Users');
}
public function testFindUser(){
$query = $this->Users->find('user', [
'fields' => ['Users.id', 'Users.email', 'Users.password',
'Users.username'],
'conditions' => ['Users.id' => 900000]
]);
$this->assertInstanceOf('Cake\ORM\Query', $query);
$result = $query->hydrate(false)->toArray();
$expected = [
[
'id' => 900000,
'email' => 'usuariocomum1#gmail.com',
'password' => 'usuariocomum1senha',
'username' => 'usuariocomum1username'
]
];
$this->assertEquals($expected, $result);
}
Method tested:
public function findUser(Query $query, array $options){
$query->where($options);
return $query;
}
Users Fixture:
public $records = [
[
'id' => 900000,
'email' => 'usuariocomum1#gmail.com',
'password' => 'usuariocomum1senha',
'username' => 'usuariocomum1username',
'user_type_id' => 900000,
'created' => '2015-07-17 18:46:47',
'modified' => '2015-07-17 18:46:47'
]
]
I'm Following this tutorial CakePHP 3.0 Testing
[EDIT 1]
With --verbose flag:
c:\xampp\htdocs\PROJETOS\Shopping>vendor\bin\phpunit --verbose tests\TestCase\Mo
del\Table\UsersTableTest
PHPUnit 4.8.6 by Sebastian Bergmann and contributors.
Runtime: PHP 5.6.3
Configuration: C:\xampp\htdocs\PROJETOS\Shopping\phpunit.xml.dist
III.
Time: 15.87 seconds, Memory: 7.50Mb
There were 3 incomplete tests:
1) App\Test\TestCase\Model\Table\UsersTableTest::testInitialize
Not implemented yet.
C:\xampp\htdocs\PROJETOS\Shopping\tests\TestCase\Model\Table\UsersTableTest.php:
58
2) App\Test\TestCase\Model\Table\UsersTableTest::testValidationDefault
Not implemented yet.
C:\xampp\htdocs\PROJETOS\Shopping\tests\TestCase\Model\Table\UsersTableTest.php:
71
3) App\Test\TestCase\Model\Table\UsersTableTest::testBuildRules
Not implemented yet.
C:\xampp\htdocs\PROJETOS\Shopping\tests\TestCase\Model\Table\UsersTableTest.php:
81
OK, but incomplete, skipped, or risky tests!
Tests: 4, Assertions: 2, Incomplete: 3.
[EDIT 2]
When I change test to:
public function testFindUser(){
$query = $this->Users->find('user', [
'fields' => ['Users.id', 'Users.email', 'Users.password',
'Users.username', 'Users.user_type_id', 'Users.created',
'Users.modified'],
'conditions' => ['Users.id' => 900000]
]);
$this->assertInstanceOf('Cake\ORM\Query', $query);
$result = $query->hydrate(false)->toArray();
$expected = [
[
'id' => 900000,
'email' => 'usuariocomum1#gmail.com',
'password' => 'usuariocomum1senha',
'username' => 'usuariocomum1username',
'user_type_id' => 900000,
'created' => '2015-07-17 18:46:47',
'modified' => '2015-07-17 18:46:47'
]
];
$this->assertEquals($expected, $result);
}
the test is executed but fails (hidrate(false) could make created and modified primitive objects)(Why now works? why 'user_type_id' => 900000 displayed)
my console:
c:\xampp\htdocs\PROJETOS\Shopping>vendor\bin\phpunit tests\TestCase\Model\Table\
UsersTableTest
PHPUnit 4.8.6 by Sebastian Bergmann and contributors.
IIIF
Time: 8.13 seconds, Memory: 7.75Mb
There was 1 failure:
1) App\Test\TestCase\Model\Table\UsersTableTest::testFindUser
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
## ##
'user_type_id' => 900000
- 'created' => '2015-07-17 18:46:47'
- 'modified' => '2015-07-17 18:46:47'
+ 'created' => Cake\I18n\Time Object (...)
+ 'modified' => Cake\I18n\Time Object (...)
)
)
C:\xampp\htdocs\PROJETOS\Shopping\tests\TestCase\Model\Table\UsersTableTest.php:
107
FAILURES!
Tests: 4, Assertions: 2, Failures: 1, Incomplete: 3.
[EDIT 3]
I clean my TestCase and delete all not implemented test (created by bake) and this is the output:
c:\xampp\htdocs\PROJETOS\Shopping>vendor\bin\phpunit tests\TestCase\Model\Table\
UsersTableTest
PHPUnit 4.8.6 by Sebastian Bergmann and contributors.
.
Time: 6.06 seconds, Memory: 7.50Mb
OK (1 test, 2 assertions)
**NOTE** CakePHP 3.0.11 PHPUnit 4.8.6
We had this in your other question, hadn't we? The testFindUser test is not being skipped, it runs just fine as you can tell from the PHPUnit output, and from the fact that you receive a failure message when you change your code so that it produces and error, if it were skipped, there would have been no failures, and the output would have been IIIS.
OK, but incomplete, skipped, or risky tests!
Tests: 4, Assertions: 2, Incomplete: 3.
* emphasis mine
4 tests in total, 3 incomplete, = 1 test ran
The message just says that there are incomplete/non-implemented tests, additionally to the tests that ran OK.
The verbose level output makes this even more clear, in showing you exactly which tests are incomplete - none of them is your testFindUser test.
You may want to have a closer look at the docs, to get a grasp on how to interpret the output.
https://phpunit.de/manual/current/en/textui.html

Using Memcached in CodeIgniter 3.0

Here is my model file;
function yaklasan_maclar_tenis() {
$data = $this->cache->memcached->get('yaklasan_tenis');
if (!$data){
$this -> db -> limit(10);
$data = array();
foreach ($this->db->get_where('maclar', array('durum' => '1', 'sonuclandi' => '0', 'tarih >=' => time(), 'spor' => '5'))->result_array() as $row) {
$data[] = array(
'id' => $row['id'],
'matchid' => $row['matchid'],
'spor' => $row['spor'],
'ulke' => $row['ulke'],
'turnuva' => $row['turnuva'],
'takim1' => $row['takim1'],
'takim2' => $row['takim2'],
'tarih' => $row['tarih'],
'istatistik' => $row['istatistik'],
);
}
$this->cache->memcached->save('yaklasan_tenis',$data, 600);
}
return $data;
}
I'm sure that I installed memcached properly but getting this error when I call this function:
Fatal error: Call to a member function get() on a non-object in /home/mydomain/public_html/system/libraries/Cache/drivers/Cache_memcached.php on line 79
Here is the lines 77-82, Cache_memcached.php file:
public function get($id)
{
$data = $this->_memcached->get($id); //this line is 79
return is_array($data) ? $data[0] : $data;
}
I made my research on site but couldn't find anything about it. I just found something and tried the suggestion but nothing changed.
Thanks in advance.
Did you load the caching drive?
Something likes:
$this->load->driver('cache', array('adapter' => 'apc', 'backup' => 'file'));

Categories