PHPUnit only runs first file in directory - phpunit

In a directory I have two files
oneTest.php
<?php
class oneTest extends PHPUnit_Framework_TestCase {
public function testSomethingOne()
{
echo 'ONE TEST';
$this->assertEquals(1, 1);
}
}
twoTest.php
<?php
class twoTest extends PHPUnit_Framework_TestCase {
public function testSomethingTwo()
{
echo 'TWO TEST';
$this->assertEquals(2, 2);
}
}
From within the directory I can run both tests fine
phpunit oneTest.php
phpunit twoTest.php
And I get the expected output on both.
If I try and run all tests with
phpunit *
It only runs the first test.
I'm running phpunit 3.6.12 on Ubuntu 12.04.
Any ideas why this is happening?
Thanks

This is simply a limitation of phpunit, it is not programmed to support multiple files on the command line. You can, however, pass a directory name to phpunit. If you want to run the tests in the current directory, use
phpunit .
Edit: alternatively, you can specify a testsuite in a XML configuration file.

Related

I want to test my command with codeception

I want to test my command with codeception but when i run test i get an error
The syntax of the file, directory, or volume name is incorrect.
This is my code for test
public function tryToTest(ApiTester $I)
{
$I->runShellCommand('talan:create:elastic:index', ['index_name' => 'bddoc', 'attachment' => 'attachment']);
$I->seeResultCodeIs(0);
}
my command work perfectly
php bin/console test:create:elastic:index bddoc attachment
I just took a look into the source code of Codeception. You just use the complete string of your command in the first parameter, and the second one is a bool variable, with let the test automatically fail, if the command does not return a integer == 0
Here is the documentation: https://codeception.com/docs/modules/Cli
function tryToTest(ApiTester $I)
{
$I->runShellCommand('php bin/console test:create:elastic:index bddoc attachment');
$I->seeResultCodeIs(0);
}

How to setup which Symfony environment is used by unit tests?

I am trying to setup a new Symfony environment named travis to run unit tests in a Travis container.
I setup this environment to distinguish it from prod and from dev.
Currently, I have:
a SYMFONY_ENV=travis environment variable setup in Travis
a config_travis.yml that contains my configuration for the Travis environment
a app_travis.php which specify the environment to load
a .travis.yml:
>
language: php
php:
- "7.2.17"
services:
- mysql
install:
- composer install --no-interaction
- echo "USE mysql;\nUPDATE user SET password=PASSWORD('${MYSQL_PASSWORD}') WHERE user='root';\nFLUSH PRIVILEGES;\n" | mysql -u root
- ./bin/console doctrine:database:create --env=travis
- ./bin/console doctrine:migration:migrate --env=travis --no-interaction
script:
- ./vendor/bin/simple-phpunit
My project looks like this:
Some examples of tests I'm running:
UserTest.php which tests the User.php model:
<?php
namespace Tests\AppBundle\Entity;
use AppBundle\Entity\User;
use PHPUnit\Framework\TestCase;
use AppBundle\Entity\Responsibility;
class UserTest extends TestCase
{
public function testId()
{
$user = new User();
$id = $user->getId();
$this->assertEquals(-1, $id);
}
}
LoginControllerTest.php which tests the LoginController.php controller:
<?php
namespace Tests\AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\HttpFoundation\Response;
class LoginControllerTest extends WebTestCase
{
/*
* Test the login form
* Logins with (admin, password : a)
*/
public function testLogin()
{
// Create a new client to browse the app
$client = static::createClient();
$crawler = $client->request('GET', '/login');
$this->assertEquals(200, $client->getResponse()->getStatusCode(), "Unexpected HTTP status code for GET ");
// Get the form
$form = $crawler->selectButton('Connexion')->form();
// Fill the login form input
$form['_username']->setValue('admin');
$form['_password']->setValue('a');
// Send the form
$client->submit($form);
$crawler = $client->followRedirect();
$this->assertContains(
'Bienvenue admin.' ,
$client->getResponse()->getContent()
);
return array($client,$crawler);
}
}
My problem is: all the command run into the travis environment, except the unit tests. I want to be able to run the unit tests in dev env on my computer but in travis env in the Travis container.
How can I setup my PHPUnit so that it can run in travis environment and use my config_travis.yml file?
The createClient() method of the WebTestCase calls the bootKernel() method from the KernelTestCase which in turn calls createKernel(). In createKernel() there is the following code which determines in which environment the kernel should be booted:
if (isset($options['environment'])) {
$env = $options['environment'];
} elseif (isset($_ENV['APP_ENV'])) {
$env = $_ENV['APP_ENV'];
} elseif (isset($_SERVER['APP_ENV'])) {
$env = $_SERVER['APP_ENV'];
} else {
$env = 'test';
}
So in your case exporting the APP_ENV variable in your config_travis.yml file and setting it to travis should solve it.
PHPUnit uses an environment variable called APP_ENV to determines which environment is used. I had to create this environment variable in Travis.

Silverstripe 4 SapphireTest class can't be found

I've upgraded from SilverStripe 3 to 4 and now my phpUnit tests own't run because they can't find any of my Custom Classes.
There must be something missing from an autoloader or something.
I have a simple test like this
use SilverStripe\Dev\SapphireTest;
class EntityTest extends SapphireTest
{
var $Entity;
function setUp()/* The :void return type declaration that should be here would cause a BC issue */
{
parent::setUp(); // TODO: Change the autogenerated stub
$this->Entity = new \My\API\Client\Model\Entity();
}
function testMethods(){
$this->assertMethodExist($this->Entity,'setName');
}
function assertMethodExist($class, $method) {
$oReflectionClass = new ReflectionClass($class);
assertThat("method exist", true, $oReflectionClass->hasMethod($method));
}
}
and when running I get:
$ php vendor/phpunit/phpunit/phpunit mysite/tests/EntityTest.php
Fatal error: Class 'SilverStripe\Dev\SapphireTest' not found
I ran into a similar issue with SilverStripe 4.1, here is what I found (and resolved).
1) As of 4.1, you need to use --prefer-source instead of --prefer-dist to get the test code. Test code is now omitted from the distributed packages, see https://github.com/silverstripe/silverstripe-framework/issues/7845
2) phpunit must be in require-dev at version ^ 5.7 - I had a different value and this was the cause of the autoload issue.
I've created a test module for reference, see https://github.com/gordonbanderson/travistestmodule
Cheers
Gordon
You're probably missing the test bootstrapping. SS4 still relies on the SilverStripe class manifest to register available classes (not just PSR-4 autoloaders), so you need to include it. Try either of these:
$ vendor/bin/phpunit --bootstrap vendor/silverstripe/framework/tests/bootstrap.php mysite/tests
or create a phpunit.xml file in your root project:
<phpunit bootstrap="vendor/silverstripe/framework/tests/bootstrap.php" colors="true">
</phpunit>
You may also use the equivalent file from the CMS module instead, but you probably won't see any differences until you start to integrate your testsuite into a CI provider.

PHPunit coverage

Hello again SO!
I'm trying to get PHPunit to run on localhost, here are some of my specs
xDebugger : v 2.2 (enabled)
php : 5.4.3
PHPunit : tried with 3.7.31 && 4.0.17
Running tests works fine, However whenever I use the coverage-html the output is always 0% covered. I've tried this with both version of PHPunit.
Whenever i try the --coverage-text command I get the same result, the tests run fine(fail/success), however the coverage is 0%.
1 test - 1 assertion - 0
For simplicity, I created these two classes :
class my
{
function method()
{
$bool = true;
echo $bool;
}
}
and the test class :
require_once 'my.php';
class myTest extends PHPUnit_Framework_TestCase
{
function testequal()
{
$bool = true;
echo $bool;
$this->assertTrue($bool);
}
}
two different files, the file names are my.php and myTest.php.
If I can provide anymore information please let me know, Thanks in advance.
You're actually not testing the code of my. Isn't it? That's why the coverage is 0%.
Change the test code to this:
require_once 'my.php';
class myTest extends PHPUnit_Framework_TestCase
{
function testSomething()
{
$object = new my();
$this->assertEquals('1', $object->method());
}
}

PHPUnit inclusion path issues

This one's got me stumped. I've been working with PHPUnit for a couple of months now, so I'm not that green...but I look forward to being pointed in the direction of the obvious mistake I'm making! The initialisation process outlined below works fine if I run the "app" from a browser - but PHPUnit is choking...can any one put me out of my misery?
I'm trying to test a homebrew MVC, for study purposes. It follows a typical ZF layout.
Here's the index page:
include './../library/SKL/Application.php';
$SKL_Application = new SKL_Application();
$SKL_Application->initialise('./../application/configs/config.ini');
Here's the application class (early days...)
include 'bootstrap.php';
class SKL_Application {
/**
* initialises the application
*/
public function initialise($file) {
$this->processBootstrap();
//purely to test PHPUnit is working as expected
return true;
}
/**
* iterates over bootstrap class and executes
* all methods prefixed with "_init"
*/
private function processBootstrap() {
$Bootstrap = new Bootstrap();
$bootstrap_methods = get_class_methods($Bootstrap);
foreach ($bootstrap_methods as $method) {
if(substr($method,0,5) == '_init'){
$bootstrap->$method();
}
}
return true;
}
}
Here's the test:
require_once dirname(__FILE__).'/../../../public/bootstrap.php';
require_once dirname(__FILE__).'/../../../library/SKL/Application.php';
class SKL_ApplicationTest extends PHPUnit_Framework_TestCase {
protected $object;
protected function setUp() {
$this->object = new SKL_Application();
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown() {
}
public function testInitialise() {
$this->assertType('boolean',$this->object->initialise());
}
}
But I keep stumbling at the first hurdle!!
PHP Warning: include(bootstrap.php): failed to open stream:
No such file or directory in path\to\files\SKL\Application.php on line 9
any ideas?
Use include_once or better yet require_once instead of include to include the bootstrap.php in the Application class file. Despite being already loaded include loads it again but since it's obviously not on the include path you get the error.
Thanks to Raoul Duke for giving me a push in the right direction, here's where I got to so far
1 - add the root of the application to the include path
2 - make all inclusion paths relative to the root of the application
3 - include a file in your unit tests that performs the same function, but compensates for the relative location when it is included. I just used realpath() on the directory location of the files.
The problem I have now is that the darn thing won't see any additional files I'm trying to pass it.
So, I'm trying to test a configuration class, that will parse a variety of filetypes dynamically. The directory structure is like this:
Application_ConfigTest.php
config.ini
The first test:
public function testParseFile() {
$this->assertType('array',$this->object->parseFile('config.ini'));
}
The error:
failed to open stream: No such file or directory
WTF? It's IN the same directory as the test class...
I solved this by providing an absolute (i.e. file structure) path to the configuration file.Can anyone explain to me how PHPUnit resolves it's paths, or is it because the test class itself is included elsewhere, rendering relative paths meaningless?

Resources