FAQ Database Discussion Community


Auth::attempt fails with PHPUnit TESTING

php,laravel,laravel-4,phpunit
I have a really strange behavior and I do not see where it could come from. I built an authentication system with Laravel documentation. When I save a User and try to login from the application, it works fine. However when I do the same thing in my AuthControllerTest, the...

submit a form using ajax in functional test

php,ajax,symfony2,phpunit,functional-testing
I'm creating a functional test for the inscription part of my project and I need to know how to test it if the form needs to go in an ajax request, otherwise the server will always return an empty inscription form. Looks like the submit method doesn't take an argument...

Stubbing a method in php

php,mocking,phpunit,stubbing
I have an issue where I don't know how to say, when x is called, it expects y to be called at least once and I don't care what y does, so long as its called. So if we look at this example: public static function createAction($params) { $postParams =...

Symfony2 & PHPUnit - Access getContainer()

php,symfony2,login,parameters,phpunit
I have a problem with my PHPUnit test on symfony2. To connect to my application, I use a web service, so I created a UserProvider. In my function loadUserByUsername I use symfony2 parameters saved in app/config/parameters.yml. As I'm not in a controller I need to use the global variable $kernel...

PHPUnit: Calling a child method from abstract class constructor

phpunit
I'm seeing an unexpected (to me) behaviour with PHPUnit, is this a bug, or am I doing something wrong? Simplified test case: abstract class abstractSpeaker { public function __construct($param) { $this->setSpeaker($param); $this->getSpeaker()->speak(); //bad line, causes error $this->tellSpeakerToSpeak(); //this lines ok } abstract function setSpeaker($value); abstract function getSpeaker(); function tellSpeakerToSpeak() {...

Can't run phpunit tests from command line

php,phpunit,laravel-5
I am trying to run unit tests in a new laravel 5 application, using the phpunit framework. In the root path of my laravel application I ru the following command: ./vendor/bin/phpunit /tests/ExampleTest.php And then I get the following message: You need to set up the project dependencies using the following...

How to use group in phpunit?

zend-framework,phpunit
How to invoke phpunit for zendframework module group wise. I mean when you invoke phpunit then it invoke module1 first then module2 and so on.

Testing PHPUnit to test a “__construct() must be an instance of ..” does not recognize exception

php,phpunit
I have the following code to test if the class constructor will fire the exception but PHPUnit test fail on it. I am trying to figure out what I am doing wrong. /** @test */ public function should_require_instance_of_uuid() { $this->setExpectedException('Exception'); $id = new BusinessPartnerId; } PHPunit gives the following error:...

Unit Testing a PHP Script

php,unit-testing,phpunit
I have some php scripts that are run as cronjobs. No classes and only a few functions. Id like to test the script with PHPUnit to make sure everything is working but it appears I need to rewrite the php as a class, which I dont want to do (or...

Any tool to help unit testing?

phpunit
Im using phpunit. But you know its difficulties, no possibility to mock private functions, to access private variables, etc. Is there a tool which help me? Something to turn private functions to public, turn static method to mockable, etc

Can't run tests provided in Slim Framework

php,xampp,phpunit,netbeans-8,slimframework
I'm trying to make a simple rest client for my android app. I would like to do than in TDD way, but for that I need simple working configuration for all actions (GET, POST, and so on). After some struggling I was able to make test work with get requests....

Getting More Context Around PHPUnit Test Failures

php,phpunit,automated-tests
In PHPUnit, let's say I do this: $this->assertTrue( $some_variable == "foo" ); When I run my tests with my code in a failing state, PHPUnit tells me: Failed asserting that false is true. Which is all fine and good, and I can usually track down WHY the test is failing....

Mocking service with PHPUnit in Zend Framework 2

php,unit-testing,zend-framework2,phpunit
I am trying to mock a delete Action. The delete method is inside a service, so I would like to mock the service that is requested inside the controller. This is the delete action: public function deleteAction() { try { $internId = $this->params()->fromRoute('id', 0); $this->getServiceLocator()->get('internService')->removeIntern($internId); } catch (Exception $e) {...

How to setup phpUnit in Atlassian Bamboo?

php,phpunit,bamboo
I am new to Atlassian Bamboo. I have my code on Atlassian Stash Repository, and I want to run PhpUnit test on my code using Bamboo plan. I have go through documentation but I am not able to create one. Does anyone knows about it?

How to back to window after closed frame with Selenium and PHPUnit?

php,selenium,selenium-webdriver,phpunit
I'm testing a page with frame where I click and frame automatically closes. After frame closes, the Selenium can't go back to current window and continue tests. My test: public function testMyFrame(){ $this->frame('myFrame'); //Select frame $this->byId('myButtonInFrame')->click; //Here myFrame is closed and my page don't have some frame $this->byId('otherButton')->click; } Error:...

Functional testing in Symfony2 gives me error: Failed asserting that false is true

php,symfony2,phpunit,functional-testing
I have action where I do this: return $this->redirect($this->generateUrl('url_key')); In my test I do this: $this->assertTrue($client->getResponse()->isRedirect()); But I get error: Failed asserting that false is true Where is my problem? Why I am getting error? My full test: public function testDeleteAction() { $client = static::createClient(); $client->request('GET', '/translation/delete/messages/test.key'); $client->followRedirects(); $this->assertTrue($client->getResponse()->isRedirect()); }...

Laravel Unit Test - POST Request Payload

php,laravel,phpunit
I need help in creating a unit test case for Laravel. It's an API end point accepting a json as the POST payload (NOT POST form) and basically just creating an entry in the database based on that json object. The API works fine but I'm having trouble in creating...

Phpunit yii: two fixtures to one table

yii,phpunit
In phpunit, with Yii, is possibile to create more fixtures for the same table? I would like to have different fixtures folders to be used with different unit test, to avoid problems between the various test file.

PHPUnit Mysteriously Fails On Object Constructor with require_once and $SERVER variable

php,netbeans,phpunit
I'm trying to wrap a test class around a pre-existing PHP class file that does not adhere to any PSR standard. The PHP object I'm trying to test has a constructor that accepts 1 argument. When prepping my object in setUp, my test correctly fails because there is a constructor...

PHPUnit overwrite actual method with stub

php,unit-testing,mocking,phpunit,stub
I just started playing around with PHPUnit and I was wondering if it is possible to overwrite/replace a method with a stub. I have some experience with Sinon, and with Sinon this is possible (http://sinonjs.org/docs/#stubs) I want to something like this: <?php class Foo { public $bar; function __construct() {...

PHPUnit - Cannot redeclare class when processIsolation set to false

php,unit-testing,configuration,phpunit
A similar question has been asked several times here PHPUnit loads all classes at once. Causes PHP Fatal error: Cannot redeclare class Cannot redeclare class error when generating PHPUnit code coverage report PHPUnit triggers a new fatal error Fatal error: Cannot redeclare class Validator in /some/path/to/Validator.php on line 6 The...

How To Write Acceptance Tests for Internet Explorer with: Selenium, PHPUnit and Mac OS X?

osx,internet-explorer,selenium,phpunit,acceptance-testing
I'm trying to write acceptance tests for a project using multiple browsers. All the tests run fine with: Firefox, Chrome and Safari. However, I don't know how to run them in Internet Explorer. I use: PHPUnit, Selenium and Mac OS X. I also use VirtualBox with Windows 8 and Windows...

What is the proper way to start a local PHP server, in PHP?

php,phpunit
I want to make unit tests of a web crawling library with PHPUnit. To do so, I need to set up a temporary web server in local to test properly. I can do this: exec('php -S 127.0.0.1:8888'); This looks ugly. And how can I even stop it? So, is there...

Access phpunit group parameter inside bootstrap

php,phpunit,bootstrap
I am using phpunit to test a large php project. The tests are organised in groups using @group annotation. I also have a phpunit.xml file in the root directory of my tests, which, among other things, specifies the bootstrap php file. In that file, I perform some general initialisation before...

PHPunit no tests execute on Travis CI

php,phpunit,composer-php,travis-ci
I'm been following a PHPUnit tutorial for the first time and my tests run fine locally. However, when running my tests on Travis CI, no tests are executed and my build exits with 0. My directory structure and full code can be seen on the repo. Build log from Travis...

Mocking or not registry-like object in phpunit tests

unit-testing,mocking,phpunit
I'm facing some difficulties to mock a registry-like object in my tests, this might be because of a wrong design but it always end using $this->at(x) and, IMHO, therefore tightly coupling my test with tested code. For example, my registry-like object looks like something like this ( remember that its...

Behat and Symfony data fixtures

php,symfony2,phpunit,fixtures,behat
I'm wondering is it possible to use separate database for the Behat tests? is there any way to drop and truncate database and load data fixtures with it like you can do with PHPUnit?

Symfony2 Unit Testing a service

symfony2,testing,service,phpunit
I'm still very new to symfony and really enjoying it. I'm at the stage where I've managed to create and setup a service, the service itself uses 2 dependencies: A Data API that returns json data (this is a separate library which i have implemented as a service and came...

How can I make PHPUnit ignore a file pattern?

php,zend-framework2,phpunit
I'm doing Code Coverage reports for a project and there's a ton of files that are included or required while tests are running that are not actually required to be tested or added to coverage reports (I'm using Zend Framework 2; config + Module files are the culprit here). Is...

best way to mock a global static method

php,unit-testing,testing,phpunit
my application has a logger library with the signature: final class Logger { public static method debug($msg); public static method warn($msg); public static method error($msg); } the class i want to test, another global static helper, use it as final class TestMe { public static method TestThis(){ Logger::debug('TestThis() called'); doThings();...

Cannot Change Method Name in PHPUnit

php,methods,phpunit,naming
I am running PHPUnit 4.2.2 inside a local Composer install. I'm also running PHP CodeSniffer 2.2.0. I have written this unit test: <?php include_once 'animals/Cat.php'; class CatAgeTest extends PHPUnit_Framework_TestCase{ public function testTrueIsTrue(){ $kittyAgeTest = new Cat("steak"); $result = $kittyAgeTest->getAge() >=5 && $kittyAgeTest->getAge() <= 10; $this->assertTrue($result); } } ?> It passes,...

Symfony 2 Functional test

php,symfony2,phpunit,functional-testing
I encounter an issue which doesn't make much logic to me in one of my functional tests. The test is quite simple, it just requests for the homepage, and searches for an element with a certain class in it. The homepage is for a blog that displays a list of...

PHPUnit Symfony set IP address for the client

symfony2,phpunit
I need to test behavior of the feature which depends on the users IP address. The user should be redirected to different pages depending on his IP address. I create client like that: $this->client = static::createClient(); Is there any way to do that?...

Phpunit permission test

php,testing,phpunit
I have function that take a csv file and generate file content in array. I need to write a phpunit tests. Goal is represend correctness of behavior when input is not present or unreadable (whether because the file is malformed or due to the lack of sufficient access rights). I...

phpunit and http content-type

rest,laravel,phpunit,dingo-api
I have an API built in Laravel (Dingo) and it works perfectly. However I have a problem with implementing phpunit to unit test my API class ProductControllerTest extends TestCase { public function testInsertProductCase() { $data = array( , "description" => "Expensive Pen" , "price" => 100 ); $server = array();...

Test cases to test a function phpunit

php,unit-testing,phpunit
I'm new to php unit testing, What are the valid test cases for below function. protected function validateParams($graph, $start, $destination) { if (!is_object($graph)) { throw new \InvalidArgumentException('Graph param should be an object !'); } if (empty($start)) { throw new \InvalidArgumentException('Start param is empty !'); } if (empty($destination)) { throw new...

Zendframework(1.12.11) view helper not found in phpunit

zend-framework,phpunit
I have following directory structure for view helper in my zendframework project --application --views --helpers --Test.php and configuration setting in application.ini is resources.view.helperPath = APPLICATION_PATH "/views/helpers" and configuration in Bootstrap.php is $view->setHelperPath(APPLICATION_PATH . "/views/helpers/"); in Test.php file naming convention is class Zend_View_Helper_Test extends Zend_View_Helper_Abstract {} and I am using helper...

PHPUnit intallation for CakePHP 2.4

cakephp,phpunit,composer-php
Error that I'm getting when trying to run tests: Fatal error: Class 'PHPUnit_Util_Diff' not found in Cake/TestSuite/Reporter/CakeHtmlReporter.php on line 267 As per this question, and the answers there, I need to install PHPUnit 3.6.x to avoid the missing Class error. How can I install this, now deprecated, version? I've tried...

Graphical representation of test results of phpunit

phpunit,report,summary,phing
I am using phpunit to do functional tests. I use the log-junit option to generate results in JUnit-XML format. I then use phing to read this XML and generate a HTML report. The report is fine and neat. However, I have two questions:-- Can I also show the results in...

How to unit test a data extraction method

php,unit-testing,phpunit
I have created a method which interacts with a framework, pulling out order items which have a completed status. However, how can I unit test my method to ensure it behaves correctly... class A { public function extractData() { // extract data from framework $dataCollection = FrameworkX->getDataCollection('sales/orders'); $dataCollection->filter('state', 'complete'); return...

“Unable to locate element” error without sleep instruction

php,selenium,selenium-webdriver,phpunit
I have the following Selenium test : class MyTest extends PHPUnit_Extensions_Selenium2TestCase { public function testFunction() { $this->url('https://mywebsiteurl.com'); // ... // Several selenium actions here // ... $this->byId('form-submit-button')->click(); // Submit a form to another URL $this->byId('next')->click(); } } And randomly, my test fails with the following error : PHPUnit_Extensions_Selenium2TestCase_WebDriverException: Unable to...

PHPUnit: “Class 'Eloquent' not found” when using @dataProvider

php,laravel,phpunit,composer-php
I'm running into an issue when writing unit tests with PHPUnit using @dataProvider in a Laravel app. The error I'm receiving is: PHP Fatal error: Class 'Eloquent' not found in /path/to/project/app/models/ExampleClass.php on line 7 It looks like the constant used in the dataProvider is causing the fatal. composer.json: "psr-4": {...

Symfony2 unit tests produces Fatal Error: Declaration of ContainerAwareEventManager::removeEventListener() must be compatible with

unit-testing,symfony2,controller,phpunit,fatal-error
When calling phpunit on a very simple standard test, it produces the following output and error: Command (in symfony2 root): phpunit -c build/ src Output: PHPUnit 4.1.6-6-g43914fa by Sebastian Bergmann. Configuration read from /srv/xxxxxxxxx/build/phpunit.xml PHP Fatal error: Declaration of Symfony\Bridge\Doctrine\ContainerAwareEventManager::removeEventListener() must be compatible with Doctrine\Common\EventManager::removeEventListener($events, $listener = NULL) in...

Why is PHPUnit still failing on SQL error, even though I have caught the exception

php,database,phpunit
I am trying to build a wrapper class that simplifies SQL access within my application (amongst other things). When testing my class with PHPUnit, a SQL error kills the test and spits out the error message to the console despite the fact that I have caught and handled the exception....

Laravel 5 Model mocking

php,phpunit,laravel-5,mockery
I have seen a few posts in various places about this and they all seem to have a similar answer. However for the life of me I cannot get the Mockery object working properly. The Attribute model looks like this namespace App\Models; use Illuminate\Database\Eloquent\Model; class Attribute extends Model { public...

Making PhpStorm recognise instances defined in PHPUnit setUp

php,phpunit,phpstorm
Consider the following test case: class FooTest extends \PHPUnit_Framework_TestCase { public $foo; public function setUp() { $this->foo = new Foo(); } public function testBar() { $expected = 42; $actual = $this->foo->bar(); $this->assertEqual($expected, $actual); } Because $this->foo is instantiated in setUp PhpStorm doesn't recognize it as an instance of Foo in...

WP_UnitTestCase - how to configure the include_path correctly with phpunit PHAR

wordpress,phpunit,composer-php
I'm trying to write a php unit test for my wordpress plugin and have been following the writing-wordpress-plugin-unit-tests tutorial. I've cloned the 'core.trac.wordpress.org/browser/tests/trunk/includes' locally I have installed phpunit via the PHAR mechanism as described here : https://phpunit.de/manual/current/en/installation.html#installation.requirements. I also have a composer.json configuration [14:11:[email protected]~]$ phpunit --version PHPUnit 4.7.3 by Sebastian...

phpunit no tests executed

php,phpunit
I have a 'No tests executed' with phpunit.. This line works $ phpunit install/InstallDbTest.php ... <result expected> ... $ cat suites/installtests.xml <phpunit> <testsuites> <testsuite name="database"> <file>install/InstallDbTest.php</file> </testsuite> </testsuites> </phpunit> $ phpunit -c suites/installtests.xml PHPUnit 4.7.4 by Sebastian Bergmann and contributors. Time: 130 ms, Memory: 11.25Mb No tests executed! Does anyone...

How can I test a function that uses DateTime to get the current time?

unit-testing,symfony2,datetime,phpunit,mockery
Most of the answers I have seen on StackOverflow are without using the DateTime object, and are instead using the date() function. This makes them very dirty solutions (overriding date(), mocking a protected function of the subject under test, etc). Is there a way to mock DateTime, effectively mocking the...

Define type for PHPUnit's mock objects

php,phpunit,phpdoc
I was wondering if its possible to use phpdoc to define some object in specific scope (inside a method only) as PHPUni's Mock, so in that method i can take advantage of type-hints, such as ->expected, ->methods and so on, just like when you just create the mock without addressing...

PhpStorm : Error in argument 1, char 2: option not found S

php,phpunit,phpstorm
So PHPstorm is running the PHP code fine in its console when I click run; that's great but I want to see it in the browser. So, I created a Built in Server inside project. Now, when I clicked on Run -> Run Project, I'm getting error as: "Error in...

Have to run my script twice?

php,bash,phpunit
I wrote a script that walks through each directory, while ignoring some, and does a composer install, phpunit and should work, for the most part it does - When i run it a second time ... The issue is the phpunit command. The script comes to that command and prints...

Laravel 5 package exceptions not firing Hander's render method

php,phpunit,laravel-5
I'm working on a package and using the Orchestra/Testbench package for my Unit tests. I'm trying to write a PHPUnit test that verifies the response is correct when an exception is thrown. In my repository I throw the following exception: use Acme\Common\Exceptions\ValidationException; ... throw new ValidationException($validator); I have registered the...

mocking findOneBy“field” in doctrine2 with phpunit

php,unit-testing,doctrine2,mocking,phpunit
If I mock the repository method find I get the expected results, but if I cal either findBy, findOneBy, findOneById I always get null. example: $mock->expects($this->once()) ->method('getId') ->will($this->returnValue(1)); $mockRepository->expects($this->any()) ->method('findBy') //if here I use 'find' works for all other cases always null ->will($this->returnValue($mock)); Is there a reason why this happen?...

Mocking Laravel Model::increment() with Mockery

php,laravel,phpunit,codeception,mockery
I have a line of code in a Laravel 5 event handler which looks like this: $this->event->batch->increment('attempted_jobs'); $this->event is the event which calls the handler and $this->event->batch contains my Batch model. All this does in increment the attempted_jobs column within my database, so it's fairly basic stuff. I would like...

database restore for integration tests with phpunit

php,testing,phpunit,integration-testing
I'm using phpunit and I'd like to know if there is a correct form for restoring the database before running integration tests. At the moment I'm calling an sql server script with php exec() on the testcase setUp method, but don't know if this is the best choice class...

PHPUnit ZF2 InputFilter with Custom Validator

zend-framework2,phpunit
I have the following InputFilter: <?php namespace Login\InputFilter; use Zend\InputFilter\InputFilter; /** * Class Login * * @package Login\InputFilter */ class Login extends InputFilter { /** * Construct */ public function __construct() { /** * Password */ $this->add( [ 'name' => 'password', 'required' => true, 'filters' => [ [ 'name' =>...

Mockery object argument validation issue

php,phpunit,mockery
Consider the example classes (apologies for it being so convoluted, but it's as slim as possible): class RecordLookup { private $records = [ 13 => 'foo', 42 => 'bar', ]; function __construct($id) { $this->record = $this->records[$id]; } public function getRecord() { return $this->record; } } class RecordPage { public function...

Symfony: testing custom user login

php,unit-testing,symfony2,phpunit
Just recently I got into testing pieces of a symfony application... For starters, I thought I would try and test a login form that should grant access to a private area. The users for this private area are correctly persisted to the database and have been tried on the development...

PHPUnit: Testing RestFul API with die response

php,json,api,zend-framework2,phpunit
I am trying to PHPUnit test an action in my ZF2 project. The APIs return a JSON string using die($jsonObject). This causes the PHPUnit test to stop processing and just die a JSON response. public function testStartupAction() { $this->dispatch('/api/v3/startup', "POST", array()); $this->assertJson('{"status":false,"message":"Please enter the UID","data":null}'); } assetJson method is never...

Symfony2 : PHPUnit How to use 'OR' condition in an assertion?

php,unit-testing,symfony2,phpunit
Using Symfony2 with PHPUnit, how can I use a OR condition in an assertion? In my case a client request can return codes 200 OR 302, but the assertEquals expect only one possibility. Is there any way to throw an exception is the code is not 200 AND 302? private...

How to test specific methods with PHPUnit

php,class,unit-testing,methods,phpunit
I need help with PHPUnit and some methods. How should you guys write tests in PHPUnit to reach a high code coverage for the following properties and methods? I'm pretty new to PHPUnit and could need some help. I've just write some test cases for more basic code. This class...

Get container in test class Symfony2

php,unit-testing,symfony2,phpunit,containers
how I can get container to be able getting mys services in tests classes. I found the solution to require_once dir(__FILE__). '/...../AppKernel.php;, But when I go into WebTestCase class and found protected static function createClient(array $options = array(), array $server = array()) { static::bootKernel($options); $client = static::$kernel->getContainer()->get('test.client'); $client->setServerParameters($server); return $client;...

Checking for a table row using DomCrawler

symfony2,dom,phpunit,domcrawler
I am writing a phpunit test... on my page I have several rows, one of them is like this: <tr><td>MATCH<small><span class="glyphicon glyphicon-pushpin"></span></small></td></tr> Some are like this: <tr><td>NOT A MATCH 1</td></tr> <tr><td>NOT A MATCH 2</td></tr> <tr><td>NOT A MATCH 3</td></tr> how can I run a test to check that the row with...

phpUnit: Pass argument into tearDownAfterClass from a test

php,phpunit
I'm using phpUnit. Is it possible to pass a result from another test to the tearDownAfterClass. I know it's possible to use @depends to make other tests depend on a test for data. Is it possible to pass that data to tearDownAfterClass afterwards somehow. @depends doesn't seem to work for...

Unable to find wrapper when testing Guzzle call with PHPUnit

php,codeigniter,phpunit,guzzle
I am writing a unit test for an API that I am developing. The API is written in the Codeigniter framework, that calls another API using Guzzle. The test I am writing verifies that the API call returns the correct response. The Test.php file contains the following code require '/application/libraries/apiWrappers/Breathehr.php';...

Travis CI is not case-sensitive by default?

filesystems,phpunit,composer-php,travis-ci,case-sensitive
I have a php project that has composer dependencies which are inherently tested in the code path of my unit tests. Here's my sample code: <?php // where FooBar is a composer package but I'm purposely typing it incorrectly here use \fooBaR public function appendNameToWords(array $words, $name) { $start =...

phpunit Test cases for InvalidArgumentException

php,symfony2,phpunit
Please tell how to create test cases fro below function to test exception and messages is thrown correctly. I'm using Symfony 2. public function validateParams(Graph $graph, $start, $destination) { if (!is_object($graph)) { throw new \InvalidArgumentException('Graph param should be an object !'); } if (empty($start)) { throw new \InvalidArgumentException('Start param is...

Symfony Functional Testing: how to understand why the test fails (with a 500 Error)

php,symfony2,phpunit,functional-testing
I'm writing functional tests for a controller that registers a new user in the app. The test I'm writing fails because of a 500 HTTP error. I'm using $response = $client->getResponse(); print_r($response->getContent());exit; to print the HTML to see what is happening but the HTML is incomplete in my console (PHPStorm)...

How to setup a mocked WP_Query in a WP_UnitTestCase

php,wordpress,phpunit
How do I setup a mock global $wp_query for a unit test? I basically want to setup the query so that is_single returns true. Stubbing over the function with namespaces is not an option since it clobbers the function for all remaining tests....

Vagrant: executable files are not executable

laravel,phpunit,puppet,laravel-5
I installed vagrant box using https://puphpet.com/ The problem is executable files are not executable: $ ls -la ./vendor/bin/phpunit -rwxrw-r-- 1 www-data www-data 138 Feb 6 11:07 ./vendor/bin/phpunit* I looked in my .vagrant\machines\default\virtualbox in project folder and found there: "mount_options":["dmode=775","fmode=764"]. But this file is generated automatically, so changing it is not...

PHPunit expectation on Mock object is not fulfilled

php,mocking,phpunit,expectations
Here is my class: public function __construct(Manager $moduleManager, Source\Yesno $yesNo) { $this->moduleManager = $moduleManager; $this->yesNo = $yesNo; } public function my1() { $this->moduleManager->isOutputEnabled(''); $this->yesNo->toOptionArray(); } public function my2() { $this->moduleManager->isOutputEnabled(''); $this->yesNo->toOptionArray(); } Here is my test: ... $this->observerMock = $this->getMock( 'path\to\Observer', null, [$this->moduleManagerMock, $this->yesNoMock], '', true ); ......

Mockery mock method inside closure

unit-testing,laravel-4,mocking,phpunit,mockery
I have problem unit testing method inside closure called by call_user_func() example : public function trans($lang, $callback) { $this->sitepress->switch_lang($lang); call_user_func($callback); } on controller : public function sendMail() { $foo = $baz = 'something'; $mail = $this->mailer; $this->helper->trans_c('en', function() use($foo, $baz, $mail) { $mail->send('Subject', $foo, $baz); }); } test case :...

Symfony Crawler: how to check that a link to a particular page exists

php,symfony2,phpunit,functional-testing
I'm writing some functional tests and i want to verify that the Edit link exists on the page if the user is logged in. The link is a simple <a href="/profile/22/edit">Edit</a>. How can I filter it using the Crawler component of Symfony? One solution is this: $this->assertEquals(1, $crawler->filter('html:contains("<a href="/profile/22/edit">")')->count()); But...

Adding PHPUnit to an existing Cakephp 2.0

cakephp,phpunit
Does anyone know how to add PHPUnit to an existing CakePHP 2.0 project that wasn't created using composer? I am trying to add PHPUnit to an existing CakePHP 2.0 project that wasn't created with composer and I cannot get CakePHP to see that PHPUnit is installed. I am using a...

Laravel 5.1 PHPUnit with “use DatabaseMigrations;” Produces Error when Accessing Test DB

php,laravel,phpunit,laravel-5.1
I'm just learning PHPUnit with Laravel 5.1. I'm using "use DatabaseMigrations" to migrate the test database for each test, which I set in my phpunit.xml: <php> ... <env name="DB_DATABASE" value="project_test"/> ... </php> I've setup a bunch of basic tests as I go along to check instantiation, factories, etc, but I...

how to mock parent::xxx method

php,phpunit,mockery
Is there a way? class AAA extends BBB { public function ccc() { parent::ccc(); } } I want to check parent ccc method 1 time called...

PHPUnit mock using mock

php,dependency-injection,mocking,phpunit,unit-testing
I have two class, i want to test it via PHPUnit. But something i do wrongly at mocking the stuffs. I want to altering a method what called by the first class. class One { private $someVar = null; private $abc = null; public function Start() { if ( null...

Configuring PhPUnit.phar with Atlassian Bamboo

php,unit-testing,phpunit,bamboo,atlassian
I am trying to configure PHPUnit with bamboo. I have followed all the instruction available on Bamboo Documentation about Getting started with PHP and Bamboo accordingly but I am not able to get a successful build. Here are the screen shots of my configuration panel and Error log. My Task...

Phpunit can't find abstract class

php,unit-testing,phpunit
For some reason when I try to test abstract class I get PHPUnit_Framework_MockObject_RuntimeException: Class "AbstractClass" does not exist. Here's the code AbstractClass.php <?php namespace SD\Project; abstract class AbstractClass { public function handle() { } } AbstractClassTest.php <?php require_once 'AbstractClass.php'; use SD\Project\AbstractClass; class AbstractClassTest extends PHPUnit_Framework_TestCase { public function testHandle() {...

How to check that method of a mockobject was not called only with a specific parameter?

php,unit-testing,mocking,phpunit
I have a PHPUnit_Framework_MockObject_MockObject of a Logger. In a unit test, I do not want a call to the warn method to happen with a specific string parameter doNotCallMeWithThisString. I have come this far: public function testThis() { ... $logger = $this->getMockLogger(); $logger->expects($this->exactly(0))->method('warn')->with( $this->equalTo('doNotCallMeWithThisString') ); ... } Yet this fails...

PHPUnit RabbitMQ: write test for create connection function

php,phpunit,rabbitmq
I'm facing the following problem. I've wrote a function that create a connection object (AMQPConnection) given the required parameters. Now I want to write the corresponding unit test. I just don't know how to do it without having the RabbitMQ broker running. Here is the function in question: public function...

Argument 1 passed to Foo::__construct() must be an instance of Psr\Log\LoggerTrait, instance of Mock_Trait_LoggerTrait_65811a25_bdddd884 given

php,unit-testing,mocking,phpunit,trait
I'm trying to mock a simple trait with PHPUnit but it is resulting on a FatalError, it works if I remove the type hinting: Argument 1 passed to Foo::__construct() must be an instance of Psr\Log\LoggerTrait, instance of Mock_Trait_LoggerTrait_65811a25_bdddd884 given The class: use Psr\Log\LoggerTrait; class Foo { /** * @var LoggerTrait...

Validating HTTP Response Codes in PHPUnit

php,unit-testing,phpunit
I am writing unit tests for several methods which return HTTP response codes. I cannot find a way to assert an HTTP response code. Perhaps I am missing something obvious, or I am misunderstanding something about PHPUnit. I am using PHPUnit 4.5 stable. Relevant part of class Message: public function...

Many test cases to cover a function - phpunit

php,unit-testing,symfony2,phpunit
For the following function I need to write more test cases, I have already written one, can someone give some ideas, Perhaps to test return values of intermediate function calls. public function calculateShortestPath($graphObj, $start, $destination) { $shortestPath = null; if ($this->validateParams($graphObj, $start, $destination) == true) { $result = $this->getAllVerticesAndNeighbours($graphObj); $vertices...

PHPUnit - Fatal error: Method PHPUnit_Framework_AssertionFailedError::__toString() must not throw an exception in… when a test class is empty?

php,phpunit
I have just started learning PHPUnit, when I create an empty class like this one: <?php namespace some\ns; use some\ns\AClass; /** * Test class for the some\ns\AClass class */ class AClassTest extends \PHPUnit_Framework_TestCase { } When I run the test: $ phpunit -c . PHPUnit 4.3.5 by Sebastian Bergmann. Configuration...

Cakephp 3 - MissingDatasourceConfigException when running phpunit test

php,unit-testing,cakephp,phpunit,cakephp-3.0
I am trying to run some unit tests in CakePHP 3 with PHPUnit 4.7.3, but I`m getting the following error: PHPUnit 4.7.3 by Sebastian Bergmann and contributors. There was 1 error: 1) App\Test\TestCase\Model\Table\MoviesTableTest::testFindMoviesByGenre Cake\Datasource\Exception\MissingDatasourceConfigException: The datasource configuration "default" was not found. C:\xampp\htdocs\movie-pal\vendor\cakephp\cakephp\src\Datasource\ConnectionManager.php:188 C:\xampp\htdocs\movie-pal\vendor\cakephp\cakephp\src\ORM\TableRegistry.php:191...

Cannot connect to DB when setting up Codeception

php,mysql,pdo,phpunit,codeception
I am attempting to setup Codeception for the first time, however when I run run --debug I get a DB connection error, yet I cannot find where the configuration is to change this. [email protected] /var/www/crmpicco (confirmation)$ php vendor/codeception/codeception/codecept run --debug Codeception PHP Testing Framework v1.9-dev Powered by PHPUnit 3.7.28 by...

phpunit testing expectedException not working

php,exception,phpunit
I am trying to test my class for InvalidArgumentException but I get Tests\BarTest::should_receive_parameter Missing argument 1 for Itdc\Foo\Bar::__construct(), called in /mypath/foo/tests/BarTest.php on line 10 and defined This is the test (BarTest.php) file I use: <?php namespace Tests; use Itdc\Foo\Bar; class BarTest extends \PHPUnit_Framework_TestCase { /** @test */ public function should_receive_parameter()...

PhpUnit Testing stub method multiple return

php,symfony2,phpunit
I am doing some PHPUnit testing with symfony2. I am having a problem with one particular test. I am testing a response form one of my Class of course one response is true one false. I have a Mock of my Database and I have a stub for one of...

PHPUnit: dataProvider not working in the sub classes of PHPUnit_Framework_TestCase

php,unit-testing,phpunit
I'm using classes extended from PHPUnit_Framework_TestCase in my tests. And it seems like the @dataProvider doesn't work for these extended classes. Here's just a simple test namespace HH\Api\V10; class StupidityTest extends TestCase { /** * @dataProvider additionProvider */ public function testAdd($a, $b, $expected) { $this->assertEquals($expected, $a + $b); } public...

assertEqual not works when testing equals of command output

php,unit-testing,symfony2,phpunit,command-line-interface
Here is what I output in my command: $output->writeln("\033[37;42m Translations from " . $input->getArgument('bundle') . " imported successfully! \033[0m"); Here is what I get in command line with trim func to delete spaces: trim($commandTester->getDisplay()) ..string(69) " Translations from AcmeDemoBundle imported successfully! " But when I run this: $this->assertEquals(" Translations from...

PHPUnit The current node list is empty

php,symfony2,testing,phpunit
I am creating some functional tests to test my controller. I have 2 functions at the moment. 1 for loggin in and 1 for the entity life cycle. both should run normally (I guess). Yet I am getting the following error: The current node list is empty I tried removing...

Should I create extra functions to make my code testable?

php,unit-testing,testing,phpunit
I am creating an application which depending on the day that it runs, it creates different reports. So if it is Monday @ 1am, It will create a weekly report, if it is the 1st of the month @ 1.30am, it will create a monthly report. My initial approach uses...

Laravel 5.1 Unable to Run Test on User Password Mutator

php,unit-testing,laravel,phpunit,laravel-5.1
I have a password mutator: /** * Mutator for setting the encryption on the user password. * * @param $password */ public function getPasswordAttribute($password) { $this->attributes[ 'password' ] = bcrypt($password); } That I'm trying to test: /** * A basic check of password mutator. * * @return void */ public...

Phpunit coverage: what is the difference between 'addUncoveredFilesFromWhitelist' and 'processUncoveredFilesFromWhitelist' options?

php,phpunit
I'm trying to set up code coverage for phpunit for a particular directory. Can someone tell me what is the difference between: <filter> <whitelist> <directory suffix=".php">lib/</directory> </whitelist> </filter> and <filter> <whitelist addUncoveredFilesFromWhitelist="true"> <directory suffix=".php">lib/</directory> </whitelist> </filter> and <filter> <whitelist processUncoveredFilesFromWhitelist="true"> <directory...

Symfony2: changing the request class and updating the test environment

php,symfony2,request,phpunit
I have modified the base Request class of my application as explained in the accepted answer of this question. It works very well, except when launching my functional tests, I get the following error: Controller "My\Bundle\AppBundle\Controller\MyController::searchAction()" requires that you provide a value for the "$request" argument (because there is no...

PHPunit call magic methods

methods,mocking,phpunit,magic-methods
I have magic method getData. Is it possible to call following inside unit test: $this->attributeMock ->method('getData') ->with('additional_data') ->willReturn('some value'); $this->attributeMock ->method('getData') ->with('is_default') ->willReturn('something'); When I do this, I got: Failed asserting that two strings are equal. --- Expected +++ Actual @@ @@ -'is_default' +'additional_data' Is there some another way?...

How can I run PHPUnit with CakePHP tests with phpunit.xml?

cakephp,phpunit
I want to run a AllModelTest with phpunit command. But when I try to run, there is nothing to test as a result. Of course, there are many test codes. $vendors/bin/phpunit --configuration app/Test/phpunit.xml PHPUnit 3.7.38 by Sebastian Bergmann. Configuration read from /Develop/web/app/Test/phpunit.xml Time: 30 ms, Memory: 3.75Mb No tests executed!...

PHPUnit symfony2 faking parameters.yml

symfony2,phpunit
I need to test some functionality with PHPUnit. I got isolated database for running tests but still some functionality depends on the parameters.yml where I add user IDs or IP addresses. Is there any way of creating fake parameters.yml for tests?