I am trying to execute some test in PHPUnits but it's not getting executed.
<?php
use \PHPUnit\Framework\TestCase;
class UserControllerTest extends TestCase {
public function testThatCanGetNumber() {
$mock = $this->getMockBuilder('UserModel')
->setMethods(array('getNumber'))
->getMock();
$mock->expects($this->once())
->method('getNumber')
->with($this->equalTo(5));
}
}
However, if I extend the class with \PHPUnit_Framework_TestCase it gets executed. Why is that?
This is my phpunit.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<phpunit bootstrap="vendor/autoload.php"
colors="true"
verbose="true"
stopOnFailure="false">
<testsuites>
<testsuite name="Test suite">
<directory>tests</directory>
</testsuite>
</testsuites>
</phpunit>
You expect that the method is getting called but you are not executing anything in the test. You should call the method where the mocked method is called.
Related
I'm new to testing in Laravel with PHPUnit. So please be patient with me.
I'm sure it is a beginner issue, but actually I cannot find the reason.
I've created my first unit test with Laravel. This test is running without issues and gives me a valid result.
This is my first created test (WoodWoodConnectionTest.php):
<?php
namespace Tests\Unit\Verification\Module\HCW;
use Tests\TestCase;
class WoodWoodConnectionTest extends TestCase {
public function testVerifyWoodWoodCalculationFormulasBasedOnValuesOfExampleReport() {
//Arrange
$verificationDataOfHCW = new \App\Models\Nachweis\Daten\HCW();
$verificationDataOfHCW->connection_type = \Config::get('constants.verbindungstyp.holzholz');
$verificationDataOfHCW->service_class = \Config::get('constants.nutzungsklasse.nkl1');
...
$calculationRepository = \App::make('\App\Repositories\Nachweis\HCWRepositoryImpl');
//Act
$calculationRepository->calculate($verificationDataOfHCW);
//Assert
$this->assertEquals(28.80, $verificationDataOfHCW->f_v_0_rk);
$this->assertEquals(1.3, $verificationDataOfHCW->y_m);
...
}
}
So I copied the test (and renamed the class, the file and the method) and modified it (WoodConcreteConnectionTest.php).
<?php
namespace Tests\Unit\Verification\Module\HCW;
use Tests\TestCase;
class WoodConcreteConnectionTest extends TestCase {
public function testVerifyWoodConcreteCalculationFormulasBasedOnValuesOfExampleReport() {
//Arrange
$verificationDataOfHCW = new \App\Models\Nachweis\Daten\HCW();
$calculationRepository = \App::make('\App\Repositories\Nachweis\HCWRepositoryImpl');
//Act
$calculationRepository->berechnen($verificationDataOfHCW);
//Assert
$this->assertTrue(true);
}
}
But when I run
php artisan test
it runs only the last created test (my copy WoodConcreteConnectionTest.php). The first one is not being executed anymore.
Same situation, when I create a new test with
php artisan make:test TestTest --unit
...it only runs this test.
UPDATE
I noticed when I change the TestCase to PHPUnit's TestCase instead of Laravel's TestCase, two tests are executed (WoodConcreteConnectionTest and TestTest).
use PHPUnit\Framework\TestCase;
//use Tests\TestCase;
...but then I cannot use my config settings or commands like this:
\App::make('\App\Repositories\Nachweis\HCWRepositoryImpl');
My Laravel TestCase class looks like this:
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
}
...and the CreatesApplication trait looks like this:
<?php
namespace Tests;
use Illuminate\Contracts\Console\Kernel;
trait CreatesApplication
{
/**
* Creates the application.
*
* #return \Illuminate\Foundation\Application
*/
public function createApplication()
{
$app = require __DIR__.'/../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
return $app;
}
}
This is my phpunit.xml
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="Feature">
<directory suffix="Test.php">./tests/Feature</directory>
</testsuite>
<testsuite name="Unit">
<directory suffix="Test.php">./tests/Unit</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./app</directory>
</whitelist>
</filter>
<php>
<env name="APP_ENV" value="testing"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="QUEUE_DRIVER" value="sync"/>
</php>
</phpunit>
Are there any other locations in a Laravel project which controls the testing?
I created fresh Symfony 4.1.x project, but when I'm trying to create and execute functional test I am getting error:
PHP Fatal error: Class
'Symfony\Bundle\FrameworkBundle\Test\WebTestCase' not found in
/home/tomasz/my_project/tests/ExampleControllerTest.php on line 7
Steps to reproduce:
Create project
composer create-project symfony/skeleton my_project
Install phpunit, functional tests components and maker for generating skeleton of functional test
composer req --dev symfony/phpunit-bridge symfony/css-selector symfony/browser-kit symfony/maker-bundle
Create example functional test
bin/console make:functional-test ExampleControllerTest
Content of created file:
<?php
namespace App\Tests;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class ExampleControllerTest extends WebTestCase
{
public function testSomething()
{
$client = static::createClient();
$crawler = $client->request('GET', '/');
$this->assertSame(200, $client->getResponse()->getStatusCode());
$this->assertContains('Hello World', $crawler->filter('h1')->text());
}
}
Run tests
bin/phpunit
Output (after installing phpunit dependencies):
PHP Fatal error: Class
'Symfony\Bundle\FrameworkBundle\Test\WebTestCase' not found in
/home/tomasz/my_project/tests/ExampleControllerTest.php on line 7
I checked and class Symfony\Bundle\FrameworkBundle\Test\WebTestCase does exist in vendor/. Any clues?
phpunit.xml.dist
<?xml version="1.0" encoding="UTF-8"?>
<!-- https://phpunit.de/manual/current/en/appendixes.configuration.html -->
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/6.5/phpunit.xsd"
backupGlobals="false"
colors="true"
bootstrap="vendor/autoload.php"
>
<php>
<ini name="error_reporting" value="-1" />
</php>
<testsuites>
<testsuite name="Project Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory>src</directory>
</whitelist>
</filter>
<listeners>
<listener class="Symfony\Bridge\PhpUnit\SymfonyTestsListener" />
</listeners>
</phpunit>
I have set up the PHPunit Framework for testing and upon running a simple test I am getting a TypeError below:
SampleTest::testTrueAssertsToTrue
TypeError: Argument 3 passed to
SebastianBergmann\GlobalState\Snapshot::__construct() must be of the type boolean, null given, called in /usr/share/php/PHPUnit/Framework/TestCase.php on line 2412
My test case is below:
class SampleTest extends \PHPUnit_Framework_TestCase
{
public function testTrueAssertsToTrue()
{
$this->assertTrue(true);
}
}
The PHPunit version is ^6.2 and below is the configuration XML file:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php"
colors="true"
verbose="true"
stopOnFailure="false">
<testsuites>
<testsuite name ="Test suite">
<directory>tests</directory>
</testsuite>
</testsuites>
</phpunit>
Please help I have searched online whole day and I cant find a solution.
Because you're using phpunit 6.2, \PHPUnit_Framework_TestCase has been removed and you should be instead extending the namespaced PHPUnit\Framework\TestCase
<?php
use PHPUnit\Framework\TestCase;
class SampleTest extends TestCase
{
public function testTrueAssertsToTrue()
{
$this->assertTrue(true);
}
}
You can verify the successful build here on travis-ci:
https://travis-ci.org/scratchers/phpunit6truetest/builds/242989226
I'm using PHPUnit with Mockery, the latter i installed via composer:
"require-dev": {
"mockery/mockery": "0.9.*"
},
Now, consider the following test case
<?php
use Mockery as m;
class FooTest extends PHPUnit_Framework_TestCase {
function testFoo() {
m::mock('DateTime');
}
}
phpunit run fine. Now consider the following:
use Mockery as m;
/**
* #runTestsInSeparateProcesses
* #preserveGlobalState disabled
*/
class FooTest extends PHPUnit_Framework_TestCase {
function testFoo() {
m::mock('DateTime');
}
}
In this case i get a Class 'Mockery' not found exception.
Mockery is not found - actually, nothing in the /vendor directory is found, as if the composer autoloading is totally messed up. I've ran both composer update and composer dump-autoload.
phpunit.xml
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
>
<testsuites>
<testsuite name="Package Test Suite">
<directory suffix=".php">./tests/</directory>
</testsuite>
</testsuites>
</phpunit>
I'm using PHPUnit 3.7.10 and i run tests with command line phpunit without any args.
How can i fix this?
Upgrading to PHPUnit 4.x fixed this issue for me.
Everytime an assert fails in my PHP code, the PHPUnit command line hangs for ever. I expected it will show the error (assert) and move on to the next test. Is that not expected?
Here is my code:
class MyTest extends PHPUnit_Framework_TestCase
{
public function testSomething()
{
// send async request
// wait for request to complete
$this->assert(<something>);
}
}
phpunit just sits there forever when is false. I tried different kind of asserts to no help.
PHPUnit config is pretty simple actually.
<phpunit bootstrap="vendor/autoload.php">
<testsuites>
<testsuite name="name">
<file>tests/ATest.php</file>
<file>tests/BTest.php</file>
<file>tests/CTest.php</file>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory>src</directory>
</whitelist>
<blacklist>
<directory>src/models</directory>
</blacklist>
</filter>
</phpunit>
The assert is also nothing special.
For example, checking if some string is non-empty.
$this->assert("" !== $model->getId(), "ID is required.")