PHPUnit: Call to undefined method - phpunit

I want to run simple player inserting test.
My code is something like that:
class Player{
public $id;
public $name;
}
class PlayerDAO{
//db stuff
.....
privatefunction input($player){
$player->id = mysql_real_escape_string($player->id);
$player->name = mysql_real_escape_string($player->name);
return $player;
}
public function insert($player){
$player = $this->input($player);
mysql_query("INSERT INTO player (name) VALUES ('.$player->name.')");
}
public function countPlayers(){
$r = mysql_query("SELECT * FROM player");
return mysql_num_rows($r);
}
}
//Test class
class PlayerTest extends PHPUnit_Framework_TestCase {
public function testInsert(){
$player = new Player();
$player->name = 'Test name';
$count1 = PlayerDAO::countPlayers();
PlayerDAO::insert($player);
$count2 = PlayerDAO::countPlayers();
$this->assertEquals(($count2-$count1), 1);
}
}
If i run test, i get error message: Fatal error: Call to undefined method PlayerTest::input() in ...PlayerTest.php. If i remove method input() from insert() method, the error message is gone.

Related

PHPUnit 9.5 set mock (or stub or fake) to the function that calling within the class

I have a function to implement Unit test function. This function is calling a other function within the same class. I want to set pre-defined returns for this calling function (functwo()).
The project is using 'Zend_Test_PHPUnit' PHPUnit 9.5.20
I have a class like this:
class myClass {
public $x;
public $y;
public $z;
public function __constructor($x, $y, $z){
$this->x = $x;
$this->y = $y;
$this->z = $z;
}
public function funcone()
{
$i = 1;
$a = $i + $this->functwo();
return $a;
}
public function functwo()
{
return 3;
}
}
And my Testing class is:
class ControllerTestCase extends Zend_Test_PHPUnit_ControllerTestCase
{
...
}
class myClassTest extends ControllerTestCase
{
public function testCheck1()
{
$x = true;
$y = 10.5;
$z = [];
$mock = $this->getMockBuilder(myClass::class)
->setConstructorArgs([$x, $y, $z])
->getMock();
$mock->method('functwo')->willReturn(5);
$result = $mock->funcone();
$this->assertTrue($result === 6);
}
}
I still getting the null for $result and it seems testing is not calling funcone(). Any idea where I am got wrong?
There was 1 failure:
1) myClassTest::testCheck1
Failed asserting that false is true.

phpunit must be traversable or implement interface Iterator

I'm trying to unit test my service, containing a dependency Finder Component of symfony2(http://symfony.com/doc/current/components/finder.html).
I'm getting :
[Exception] Objects returned by Mock_Finder_91776c5c::getIterator()
must be traversable or implement interface Iterator
The service :
public function getFile($fileName, $path = '/')
{
if($this->wrapper == null || $this->connection == null)
throw new LogicException("call method setFTP first");
// get file on ftp server
$this->connection->open();
$downloadComplete = $this->wrapper->get($this->tmpDir . $fileName, $path . $fileName);
$this->connection->close();
if($downloadComplete == false)
return false; // TODO exception ?
// return file downloaded
$this->finder->files()->in(__DIR__);
foreach ($this->finder as $file) {
return $file;
}
return false; // TODO exception ?
}
And the test
class FtpServiceTest extends \PHPUnit_Framework_TestCase
{
protected $connectionMock;
protected $ftpWrapperMock;
protected $finderMock;
protected function setUp()
{
$this->connectionMock = $this->getConnectionMock();
$this->ftpWrapperMock = $this->getFTPWrapperMock();
$this->finderMock = $this->getFinderMock();
}
protected function tearDown()
{
}
private function getFinderMock()
{
return $this->getMockBuilder(Finder::class)
->disableOriginalConstructor()
->getMock('Iterator');
}
private function getConnectionMock()
{
return $this->getMockBuilder(Connection::class)
->disableOriginalConstructor()
->getMock();
}
private function getFTPWrapperMock()
{
return $this->getMockBuilder(FTPWrapper::class)
->disableOriginalConstructor()
->getMock();
}
// tests
public function testMe()
{
// arrange
$host = 'localhost';
$user = 'user';
$password = '1234';
$filesArray = new ArrayObject(array(''));
$service = new FtpService('var/tmp/');
$service->setFTP($this->connectionMock, $this->ftpWrapperMock);
$service->setFinder($this->finderMock);
$this->connectionMock
->expects($this->once())
->method('open');
$this->ftpWrapperMock
->expects($this->once())
->method('get')
->will($this->returnValue(true));
$this->connectionMock
->expects($this->once())
->method('close');
$this->finderMock
->expects($this->once())
->method('files')
->will($this->returnValue($this->finderMock));
$this->finderMock
->expects($this->once())
->method('in')
->will($this->returnValue($filesArray));
// act
$file = $service->getFile('/file.zip');
// assert
$this->assertInstanceOf(SplFileInfo::class, $file);
}
}
The mocked instance of the Finder class needs to implement/mock the method getIterator. The getMock method does not accept arguments so don't pass the string 'Iterator'—change the code as follows:
private function getFinderMock()
{
return $this->getMockBuilder(Finder::class)
->disableOriginalConstructor()
->getMock();
}
And add the Mocked expectation in the test method, for example:
$this->finderMock->expects($this->once())
->method('getIterator')
->willReturn(new \ArrayObject([$this->createMock(SplFileInfo::class)]));
Hope this helps.

PHPUnit Mocking Wrapper Instances

I have this wrapper:
class APIWrapper {
protected static $clientClass = \Hardcoded_API; // from a library
protected $client;
public function __construct() {
$this->client = new self::$clientClass(array_merge(self::$config, $config));
}
/**
* Does something.
*
* #throws SomeException
*/
public function act() {
$this->client->doSomething();
}
public static function setClientClass($clientClass) {
self::$clientClass = $clientClass;
}
}
Now let's say I am testing functions that make use of this wrapper:
class UnrelatedFunction {
public function callAPI() {
$wrapper = new APIWrapper();
try {
$wrapper->act();
} catch (SomeException $e) {
// ... do other things
}
}
}
class UnrelatedFunctionsTest extends PHPUnit_Framework_TestCase {
public function testUnrelatedFunctionException() {
$unrelatedFunction = new UnrelatedFunction();
$this->setExpectedException('SomeException');
// this call triggers the APIWrapper
$unrelatedFunction->callAPI();
// Some assertions here...
}
}
I need to be able to verify that UnrelatedFunction::callAPI() did its job recovering from the exception. In this case, how can I mock a \Hardcoded_API class, make it throw a SomeException when act() is called, and pass it onto APIWrapper::setClientClass() so that I can test the behaviour?

Symfony2 Service with an unique instance

Please i need some help:
I have the following services:
SERVICE CONFIGURATION IN services.yml
services:
xpad.producto_repository:
class: Xpad\ProductoBundle\Entity\ProductRepository
factory_service: doctrine.orm.clientes_entity_manager
factory_method: getRepository
arguments:
- Xpad\ProductoBundle\Entity\Product
backend_cliente.producto_filters:
class: Xpad\BackendClienteBundle\Filters\ProductFilters
calls:
- [setRepository, ["#xpad.producto_repository="]]
scope: container
AND THE CLASS FOR backend_cliente.producto_filters IS:
namespace Xpad\BackendClienteBundle\Filters;
use Xpad\ProductoBundle\Entity\ProductRepository;
class ProductFilters
{
private $_queryBuilder;
public function getQueryBuilder()
{
return $this->_queryBuilder;
}
public function setQueryBuilder($queryBuilder)
{
$this->_queryBuilder = $queryBuilder;
}
public function setRepository(ProductRepository $productRepository = null)
{
if($this->_queryBuilder == null)
{
$this->_queryBuilder = $productRepository->createQueryBuilder('p');
}
}
}
AND I HAVE THE FOLLOWING ACTION IN ONE OF MY CONTROLLERS:
class ProductController extends Controller
{
............
public function indexAction(Request $request)
{
//SOME CODE
$service_filter = $this->container->get('backend_cliente.producto_filters');
$queryBuilder = $service_filter->getQueryBuilder();
//SOME OTHER CODE
}
MY PROBLEM IS: ANYTIME THAT THE indexAction is execute I GOT A NEW INSTANCE OF backend_cliente.producto_filters SERVICE AND I DON'T KNOW WHY. I NEED AND UNIQUE INSTANCE AS A SINGLETON BECAUSE A HAVE THE $_queryBuilder ATRIBUTTE AND I NEED TO GET THE VALUE OF IT JUST MODIFY ITS VALUE WHEN IS NEEDED;
PLEASE HELP I DON KNOW WHAT I'M DOING WRONG.
Do you have to use the class as a service?
Why don't you use a Singleton, without using a service? Like this:
namespace Xpad\BackendClienteBundle\Filters;
use Xpad\ProductoBundle\Entity\ProductRepository;
class ProductFilters {
private $_queryBuilder;
private static $reference = null;
public function getInstance(){
if (self::$reference === null)
self::$reference = new ProductFilters();
return self::$reference;
}
private function __construct(){}
public function getQueryBuilder()
{
return $this->_queryBuilder;
}
public function setQueryBuilder($queryBuilder)
{
$this->_queryBuilder = $queryBuilder;
}
public function setRepository(ProductRepository $productRepository = null)
{
if($this->_queryBuilder == null)
{
$this->_queryBuilder = $productRepository->createQueryBuilder('p');
}
}
}
And call it with:
...
$filter = ProductFilters::getInstance();
...

Finding out where TypeErrors are thrown

I am having a problem that is driving me nuts.
Recently I configured my BlazeDS to use Array instead of ArrayCollection for performance reasons. Additionally I adjusted my templates to generate Array properties.
Everything wen't fine. All except one function that causes TypeError: Error #1034. These are being thrown before the result callback is called. It claims to have problems casting an ArrayCollection to Array. I removed the generated types to make Flex use Objects instead, but these did not contain any ArrayCollections. My question now is: How can I get the stack-traces of errors thrown in event-handlers?
I allready added handlers for unhandledExceptions in all of my modules and they are called if errors occur in code triggered from user-interaction, but they don't seem to be able to catch stuff thrown by event-handlers.
How can I track these Errors?
Chris
PS: The classes are:
package de.upw.ps.ucg.model.ucg.scheduler {
[Bindable]
[RemoteClass(alias="de.upw.ps.ucg.model.ucg.scheduler.Task")]
public class Task extends TaskBase {
}
}
And:
package de.upw.ps.ucg.model.ucg.scheduler {
import de.upw.ps.ucg.model.oval.common.OvalVersionedIdentifier;
import flash.utils.IExternalizable;
[Bindable]
public class TaskBase {
public function TaskBase() {}
private var _aborted:Boolean;
private var _characteristicsId:String;
private var _currentExecutorPhase:JobExecutorPhase;
private var _definitionSetName:String;
private var _definitionSetVid:OvalVersionedIdentifier;
private var _endTime:Date;
private var _enqueueTime:Date;
private var _environmentId:String;
private var _environmentName:String;
private var _messages:Array;
private var _numberOfDefinitions:int;
private var _processedNumberOfTests:int;
private var _resultsId:String;
private var _schedulerJob:SchedulerJob;
private var _startTime:Date;
private var _statusMessage:String;
private var _taskId:String;
private var _totalNumberOfTests:int;
public function set aborted(value:Boolean):void {
_aborted = value;
}
public function get aborted():Boolean {
return _aborted;
}
public function set characteristicsId(value:String):void {
_characteristicsId = value;
}
public function get characteristicsId():String {
return _characteristicsId;
}
public function set currentExecutorPhase(value:JobExecutorPhase):void {
_currentExecutorPhase = value;
}
public function get currentExecutorPhase():JobExecutorPhase {
return _currentExecutorPhase;
}
public function set definitionSetName(value:String):void {
_definitionSetName = value;
}
public function get definitionSetName():String {
return _definitionSetName;
}
public function set definitionSetVid(value:OvalVersionedIdentifier):void {
_definitionSetVid = value;
}
public function get definitionSetVid():OvalVersionedIdentifier {
return _definitionSetVid;
}
public function set endTime(value:Date):void {
_endTime = value;
}
public function get endTime():Date {
return _endTime;
}
public function set enqueueTime(value:Date):void {
_enqueueTime = value;
}
public function get enqueueTime():Date {
return _enqueueTime;
}
public function set environmentId(value:String):void {
_environmentId = value;
}
public function get environmentId():String {
return _environmentId;
}
public function set environmentName(value:String):void {
_environmentName = value;
}
public function get environmentName():String {
return _environmentName;
}
public function set messages(value:Array):void {
_messages = value;
}
public function get messages():Array {
return _messages;
}
public function set numberOfDefinitions(value:int):void {
_numberOfDefinitions = value;
}
public function get numberOfDefinitions():int {
return _numberOfDefinitions;
}
public function set processedNumberOfTests(value:int):void {
_processedNumberOfTests = value;
}
public function get processedNumberOfTests():int {
return _processedNumberOfTests;
}
public function set resultsId(value:String):void {
_resultsId = value;
}
public function get resultsId():String {
return _resultsId;
}
public function set schedulerJob(value:SchedulerJob):void {
_schedulerJob = value;
}
public function get schedulerJob():SchedulerJob {
return _schedulerJob;
}
public function set startTime(value:Date):void {
_startTime = value;
}
public function get startTime():Date {
return _startTime;
}
public function set statusMessage(value:String):void {
_statusMessage = value;
}
public function get statusMessage():String {
return _statusMessage;
}
public function set taskId(value:String):void {
_taskId = value;
}
public function get taskId():String {
return _taskId;
}
public function set totalNumberOfTests(value:int):void {
_totalNumberOfTests = value;
}
public function get totalNumberOfTests():int {
return _totalNumberOfTests;
}
}
}
Both classes are generated by my maven build from a corresponding Java Class and the Types do fit together nicely.
Do you have access to the socket class that's reading in all these messages? Trace out the buffer before the deserialisation and you should at least be able to find the class that's giving you hassle.
Failing that, trace out the object after deserialisation and it should be the very first one after the error is thrown.
This is something you'll have to debug on your own, but I have a gut feeling that the problem is because the data being sent by your java DTO is not the same as your AS3 class, even though that you have the RemoteClass metadata saying that it is.
Are you missing a property? or have a property mismatch? That is the most likely cause of your error. I suggest you debug the java side as much as you can and use something like firebug to see the request/response of the server.

Resources