kandi background
Explore Kits

phpunit | The PHP Unit Testing framework | Unit Testing library

 by   sebastianbergmann PHP Version: Current License: Non-SPDX

 by   sebastianbergmann PHP Version: Current License: Non-SPDX

Download this library from

kandi X-RAY | phpunit Summary

phpunit is a PHP library typically used in Testing, Unit Testing applications. phpunit has no bugs and it has medium support. However phpunit has 2 vulnerabilities and it has a Non-SPDX License. You can download it from GitHub.
PHPUnit is a programmer-oriented testing framework for PHP. It is an instance of the xUnit architecture for unit testing frameworks.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • phpunit has a medium active ecosystem.
  • It has 18324 star(s) with 2086 fork(s). There are 337 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 148 open issues and 2945 have been closed. On average issues are closed in 64 days. There are 28 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of phpunit is current.
phpunit Support
Best in #Unit Testing
Average in #Unit Testing
phpunit Support
Best in #Unit Testing
Average in #Unit Testing

quality kandi Quality

  • phpunit has 0 bugs and 0 code smells.
phpunit Quality
Best in #Unit Testing
Average in #Unit Testing
phpunit Quality
Best in #Unit Testing
Average in #Unit Testing

securitySecurity

  • phpunit has 2 vulnerability issues reported (1 critical, 0 high, 1 medium, 0 low).
  • phpunit code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
phpunit Security
Best in #Unit Testing
Average in #Unit Testing
phpunit Security
Best in #Unit Testing
Average in #Unit Testing

license License

  • phpunit has a Non-SPDX License.
  • Non-SPDX licenses can be open source with a non SPDX compliant license, or non open source licenses, and you need to review them closely before use.
phpunit License
Best in #Unit Testing
Average in #Unit Testing
phpunit License
Best in #Unit Testing
Average in #Unit Testing

buildReuse

  • phpunit releases are not available. You will need to build from source code and install.
  • Installation instructions, examples and code snippets are available.
  • phpunit saves you 13514 person hours of effort in developing the same functionality from scratch.
  • It has 37508 lines of code, 3537 functions and 726 files.
  • It has medium code complexity. Code complexity directly impacts maintainability of the code.
phpunit Reuse
Best in #Unit Testing
Average in #Unit Testing
phpunit Reuse
Best in #Unit Testing
Average in #Unit Testing
Top functions reviewed by kandi - BETA

kandi has reviewed phpunit and discovered the below as its top functions. This is intended to give you an instant insight into phpunit implemented functionality, and help decide if they suit your requirements.

  • Creates a new Configuration instance from provided parameters .
  • Merge a cli configuration into a new instance .
  • Returns metadata for the given class .
  • Process code coverage .
  • Returns an array of requirements that are not satisfied .
  • Creates new instance .
  • Returns the lines to be covered by the specified method .
  • Convert a DOM element to a variable .
  • Collect data provider by method name .
  • Negotiates a string .

phpunit Key Features

The PHP Unit Testing framework.

Installation

copy iconCopydownload iconDownload
$ wget https://phar.phpunit.de/phpunit-X.Y.phar

$ php phpunit-X.Y.phar --version

How to test form submission with wrong values using Symfony crawler component and PHPUnit?

copy iconCopydownload iconDownload
$form = $crawler->filter('[type=submit]')->form()->disableValidation();
$form->setValues([
    'some[name]' => 'Someokvalue',
    'some[color]' => 'SomeNOTOKValue',
];
$client->submit($form);

$this->assertEquals($entriesBefore, $repo->count([]); // Now passes.

What is the 'X' in this insert > X'3C2F756C3E'

copy iconCopydownload iconDownload
<binary string literal> ::=
  X <quote> [ <space>... ] [ { <hexit> [ <space>... ] <hexit> [ <space>... ] }... ] <quote>
    [ { <separator> <quote> [ <space>... ] [ { <hexit> [ <space>... ]
    <hexit> [ <space>... ] }... ] <quote> }... ]

<hexit> ::=
  <digit> | A | B | C | D | E | F | a | b | c | d | e | f

phpunit tests failing after going to php 8.0 because of &quot;Unknown named parameter&quot;

copy iconCopydownload iconDownload
class User {}

class Example {
     public User $user;

     public function __construct(User $user) {
          $this->user = $user;
     }
}

class ExampleTest extends PHPUnit\Framework\TestCase {
     public function testExample() {
          $args = [];
          $args['User'] = $this->getMockBuilder('User')->disableOriginalConstructor()->getMock();

          $mock = $this->getMockBuilder(Example::class)
                ->setConstructorArgs($args)
                ->getMock();

          $this->assertTrue(true);
      }
}
$class = new ReflectionClass($className);
$object = $class->newInstanceArgs($arguments);
class User {}

class Example {
     public User $user;

     public function __construct(User $user) {
          $this->user = $user;
     }
}

$class = new ReflectionClass(Example::class);
$object = $class->newInstanceArgs(['User' => new User]);
Fatal error: Uncaught Error: Unknown named parameter $User in /in/QU4jS:14
Stack trace:
#0 /in/QU4jS(14): ReflectionClass->newInstanceArgs(Array)
#1 {main}
  thrown in /in/QU4jS on line 14
class Example2 {
    public function __construct($first, $second) {
        echo "$first then $second\n";
    }
}

$class = new ReflectionClass(Example2::class);
$object = $class->newInstanceArgs(['second' => 'two', 'first' => 'one']);
class ExampleTest extends PHPUnit\Framework\TestCase {
     public function testExample() {
          $args = [];
          $args[] = new User;

          $mock = $this->getMockBuilder(Example::class)
                ->setConstructorArgs($args)
                ->getMock();

          $this->assertTrue(true);
      }
}
class ExampleTest extends PHPUnit\Framework\TestCase {
     public function testExample() {
          $args = [];
          $args['User'] = new User;

          $mock = $this->getMockBuilder(Example::class)
                ->setConstructorArgs(array_values($args))
                ->getMock();

          $this->assertTrue(true);
      }
}
-----------------------
class User {}

class Example {
     public User $user;

     public function __construct(User $user) {
          $this->user = $user;
     }
}

class ExampleTest extends PHPUnit\Framework\TestCase {
     public function testExample() {
          $args = [];
          $args['User'] = $this->getMockBuilder('User')->disableOriginalConstructor()->getMock();

          $mock = $this->getMockBuilder(Example::class)
                ->setConstructorArgs($args)
                ->getMock();

          $this->assertTrue(true);
      }
}
$class = new ReflectionClass($className);
$object = $class->newInstanceArgs($arguments);
class User {}

class Example {
     public User $user;

     public function __construct(User $user) {
          $this->user = $user;
     }
}

$class = new ReflectionClass(Example::class);
$object = $class->newInstanceArgs(['User' => new User]);
Fatal error: Uncaught Error: Unknown named parameter $User in /in/QU4jS:14
Stack trace:
#0 /in/QU4jS(14): ReflectionClass->newInstanceArgs(Array)
#1 {main}
  thrown in /in/QU4jS on line 14
class Example2 {
    public function __construct($first, $second) {
        echo "$first then $second\n";
    }
}

$class = new ReflectionClass(Example2::class);
$object = $class->newInstanceArgs(['second' => 'two', 'first' => 'one']);
class ExampleTest extends PHPUnit\Framework\TestCase {
     public function testExample() {
          $args = [];
          $args[] = new User;

          $mock = $this->getMockBuilder(Example::class)
                ->setConstructorArgs($args)
                ->getMock();

          $this->assertTrue(true);
      }
}
class ExampleTest extends PHPUnit\Framework\TestCase {
     public function testExample() {
          $args = [];
          $args['User'] = new User;

          $mock = $this->getMockBuilder(Example::class)
                ->setConstructorArgs(array_values($args))
                ->getMock();

          $this->assertTrue(true);
      }
}
-----------------------
class User {}

class Example {
     public User $user;

     public function __construct(User $user) {
          $this->user = $user;
     }
}

class ExampleTest extends PHPUnit\Framework\TestCase {
     public function testExample() {
          $args = [];
          $args['User'] = $this->getMockBuilder('User')->disableOriginalConstructor()->getMock();

          $mock = $this->getMockBuilder(Example::class)
                ->setConstructorArgs($args)
                ->getMock();

          $this->assertTrue(true);
      }
}
$class = new ReflectionClass($className);
$object = $class->newInstanceArgs($arguments);
class User {}

class Example {
     public User $user;

     public function __construct(User $user) {
          $this->user = $user;
     }
}

$class = new ReflectionClass(Example::class);
$object = $class->newInstanceArgs(['User' => new User]);
Fatal error: Uncaught Error: Unknown named parameter $User in /in/QU4jS:14
Stack trace:
#0 /in/QU4jS(14): ReflectionClass->newInstanceArgs(Array)
#1 {main}
  thrown in /in/QU4jS on line 14
class Example2 {
    public function __construct($first, $second) {
        echo "$first then $second\n";
    }
}

$class = new ReflectionClass(Example2::class);
$object = $class->newInstanceArgs(['second' => 'two', 'first' => 'one']);
class ExampleTest extends PHPUnit\Framework\TestCase {
     public function testExample() {
          $args = [];
          $args[] = new User;

          $mock = $this->getMockBuilder(Example::class)
                ->setConstructorArgs($args)
                ->getMock();

          $this->assertTrue(true);
      }
}
class ExampleTest extends PHPUnit\Framework\TestCase {
     public function testExample() {
          $args = [];
          $args['User'] = new User;

          $mock = $this->getMockBuilder(Example::class)
                ->setConstructorArgs(array_values($args))
                ->getMock();

          $this->assertTrue(true);
      }
}
-----------------------
class User {}

class Example {
     public User $user;

     public function __construct(User $user) {
          $this->user = $user;
     }
}

class ExampleTest extends PHPUnit\Framework\TestCase {
     public function testExample() {
          $args = [];
          $args['User'] = $this->getMockBuilder('User')->disableOriginalConstructor()->getMock();

          $mock = $this->getMockBuilder(Example::class)
                ->setConstructorArgs($args)
                ->getMock();

          $this->assertTrue(true);
      }
}
$class = new ReflectionClass($className);
$object = $class->newInstanceArgs($arguments);
class User {}

class Example {
     public User $user;

     public function __construct(User $user) {
          $this->user = $user;
     }
}

$class = new ReflectionClass(Example::class);
$object = $class->newInstanceArgs(['User' => new User]);
Fatal error: Uncaught Error: Unknown named parameter $User in /in/QU4jS:14
Stack trace:
#0 /in/QU4jS(14): ReflectionClass->newInstanceArgs(Array)
#1 {main}
  thrown in /in/QU4jS on line 14
class Example2 {
    public function __construct($first, $second) {
        echo "$first then $second\n";
    }
}

$class = new ReflectionClass(Example2::class);
$object = $class->newInstanceArgs(['second' => 'two', 'first' => 'one']);
class ExampleTest extends PHPUnit\Framework\TestCase {
     public function testExample() {
          $args = [];
          $args[] = new User;

          $mock = $this->getMockBuilder(Example::class)
                ->setConstructorArgs($args)
                ->getMock();

          $this->assertTrue(true);
      }
}
class ExampleTest extends PHPUnit\Framework\TestCase {
     public function testExample() {
          $args = [];
          $args['User'] = new User;

          $mock = $this->getMockBuilder(Example::class)
                ->setConstructorArgs(array_values($args))
                ->getMock();

          $this->assertTrue(true);
      }
}
-----------------------
class User {}

class Example {
     public User $user;

     public function __construct(User $user) {
          $this->user = $user;
     }
}

class ExampleTest extends PHPUnit\Framework\TestCase {
     public function testExample() {
          $args = [];
          $args['User'] = $this->getMockBuilder('User')->disableOriginalConstructor()->getMock();

          $mock = $this->getMockBuilder(Example::class)
                ->setConstructorArgs($args)
                ->getMock();

          $this->assertTrue(true);
      }
}
$class = new ReflectionClass($className);
$object = $class->newInstanceArgs($arguments);
class User {}

class Example {
     public User $user;

     public function __construct(User $user) {
          $this->user = $user;
     }
}

$class = new ReflectionClass(Example::class);
$object = $class->newInstanceArgs(['User' => new User]);
Fatal error: Uncaught Error: Unknown named parameter $User in /in/QU4jS:14
Stack trace:
#0 /in/QU4jS(14): ReflectionClass->newInstanceArgs(Array)
#1 {main}
  thrown in /in/QU4jS on line 14
class Example2 {
    public function __construct($first, $second) {
        echo "$first then $second\n";
    }
}

$class = new ReflectionClass(Example2::class);
$object = $class->newInstanceArgs(['second' => 'two', 'first' => 'one']);
class ExampleTest extends PHPUnit\Framework\TestCase {
     public function testExample() {
          $args = [];
          $args[] = new User;

          $mock = $this->getMockBuilder(Example::class)
                ->setConstructorArgs($args)
                ->getMock();

          $this->assertTrue(true);
      }
}
class ExampleTest extends PHPUnit\Framework\TestCase {
     public function testExample() {
          $args = [];
          $args['User'] = new User;

          $mock = $this->getMockBuilder(Example::class)
                ->setConstructorArgs(array_values($args))
                ->getMock();

          $this->assertTrue(true);
      }
}
-----------------------
class User {}

class Example {
     public User $user;

     public function __construct(User $user) {
          $this->user = $user;
     }
}

class ExampleTest extends PHPUnit\Framework\TestCase {
     public function testExample() {
          $args = [];
          $args['User'] = $this->getMockBuilder('User')->disableOriginalConstructor()->getMock();

          $mock = $this->getMockBuilder(Example::class)
                ->setConstructorArgs($args)
                ->getMock();

          $this->assertTrue(true);
      }
}
$class = new ReflectionClass($className);
$object = $class->newInstanceArgs($arguments);
class User {}

class Example {
     public User $user;

     public function __construct(User $user) {
          $this->user = $user;
     }
}

$class = new ReflectionClass(Example::class);
$object = $class->newInstanceArgs(['User' => new User]);
Fatal error: Uncaught Error: Unknown named parameter $User in /in/QU4jS:14
Stack trace:
#0 /in/QU4jS(14): ReflectionClass->newInstanceArgs(Array)
#1 {main}
  thrown in /in/QU4jS on line 14
class Example2 {
    public function __construct($first, $second) {
        echo "$first then $second\n";
    }
}

$class = new ReflectionClass(Example2::class);
$object = $class->newInstanceArgs(['second' => 'two', 'first' => 'one']);
class ExampleTest extends PHPUnit\Framework\TestCase {
     public function testExample() {
          $args = [];
          $args[] = new User;

          $mock = $this->getMockBuilder(Example::class)
                ->setConstructorArgs($args)
                ->getMock();

          $this->assertTrue(true);
      }
}
class ExampleTest extends PHPUnit\Framework\TestCase {
     public function testExample() {
          $args = [];
          $args['User'] = new User;

          $mock = $this->getMockBuilder(Example::class)
                ->setConstructorArgs(array_values($args))
                ->getMock();

          $this->assertTrue(true);
      }
}
-----------------------
class User {}

class Example {
     public User $user;

     public function __construct(User $user) {
          $this->user = $user;
     }
}

class ExampleTest extends PHPUnit\Framework\TestCase {
     public function testExample() {
          $args = [];
          $args['User'] = $this->getMockBuilder('User')->disableOriginalConstructor()->getMock();

          $mock = $this->getMockBuilder(Example::class)
                ->setConstructorArgs($args)
                ->getMock();

          $this->assertTrue(true);
      }
}
$class = new ReflectionClass($className);
$object = $class->newInstanceArgs($arguments);
class User {}

class Example {
     public User $user;

     public function __construct(User $user) {
          $this->user = $user;
     }
}

$class = new ReflectionClass(Example::class);
$object = $class->newInstanceArgs(['User' => new User]);
Fatal error: Uncaught Error: Unknown named parameter $User in /in/QU4jS:14
Stack trace:
#0 /in/QU4jS(14): ReflectionClass->newInstanceArgs(Array)
#1 {main}
  thrown in /in/QU4jS on line 14
class Example2 {
    public function __construct($first, $second) {
        echo "$first then $second\n";
    }
}

$class = new ReflectionClass(Example2::class);
$object = $class->newInstanceArgs(['second' => 'two', 'first' => 'one']);
class ExampleTest extends PHPUnit\Framework\TestCase {
     public function testExample() {
          $args = [];
          $args[] = new User;

          $mock = $this->getMockBuilder(Example::class)
                ->setConstructorArgs($args)
                ->getMock();

          $this->assertTrue(true);
      }
}
class ExampleTest extends PHPUnit\Framework\TestCase {
     public function testExample() {
          $args = [];
          $args['User'] = new User;

          $mock = $this->getMockBuilder(Example::class)
                ->setConstructorArgs(array_values($args))
                ->getMock();

          $this->assertTrue(true);
      }
}

Why does class autoloading not work for a package required using &quot;repositories.package&quot;?

copy iconCopydownload iconDownload
{
  "repositories": [
    {
      "type": "package",
      "package": {
        "name": "mygitlab/ach-file",
        "version": "1.2",
        "type": "package",
        "autoload": {
          "psr-4": {
            "RW\\": "src/"
          }
        }, 
         "require": {
                "ext-ssh2": "*",
                "ext-bcmath": "*"
            },
        "source": {
          "url": "https://mygitlab.ca/mygitlab/ach-file.git",
          "type": "git",
          "reference": "master"
        }
      }
    }
  ],
  "require": {
    "mygitlab/ach-file": "*"
  }
}
{
 "repositories": [
        {
            "type": "vcs",
            "url": "https://github.com/yivi/ach-file"
        }
    ],
    "require": {
        "revenuewire/ach-file": "dev-master"
    }
}

-----------------------
{
  "repositories": [
    {
      "type": "package",
      "package": {
        "name": "mygitlab/ach-file",
        "version": "1.2",
        "type": "package",
        "autoload": {
          "psr-4": {
            "RW\\": "src/"
          }
        }, 
         "require": {
                "ext-ssh2": "*",
                "ext-bcmath": "*"
            },
        "source": {
          "url": "https://mygitlab.ca/mygitlab/ach-file.git",
          "type": "git",
          "reference": "master"
        }
      }
    }
  ],
  "require": {
    "mygitlab/ach-file": "*"
  }
}
{
 "repositories": [
        {
            "type": "vcs",
            "url": "https://github.com/yivi/ach-file"
        }
    ],
    "require": {
        "revenuewire/ach-file": "dev-master"
    }
}

How to create a double for an interface, usefully, concisely and legally?

copy iconCopydownload iconDownload
$mock = $this->getMockBuilder(MyInterface::class)->getMock();

// That's. Freakin. IT.

$mock->expects($this-any())
    ->method('whatever_but_present_in_interface')
    ->willReturnCallback(function(){ return "YISS!"; });

// It. Just. Works.

Unable to get mock container to return anything but null

copy iconCopydownload iconDownload
['logger', null, $loggerMock]
['logger', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $loggerMock]
$containerMock->method('get')->will($this->returnValueMap([
   ['logger', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $loggerMock]
]));
-----------------------
['logger', null, $loggerMock]
['logger', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $loggerMock]
$containerMock->method('get')->will($this->returnValueMap([
   ['logger', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $loggerMock]
]));
-----------------------
['logger', null, $loggerMock]
['logger', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $loggerMock]
$containerMock->method('get')->will($this->returnValueMap([
   ['logger', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $loggerMock]
]));

Wrong PHP Version/Executable in VSCode terminal but works perfectly in Mac terminal

copy iconCopydownload iconDownload
nano ~/.zshrc
# If you come from bash you might have to change your $PATH.
# export PATH=$HOME/bin:/usr/local/bin:$PATH
export PATH=/opt/homebrew/opt/php@8.0/bin:$PATH
-----------------------
nano ~/.zshrc
# If you come from bash you might have to change your $PATH.
# export PATH=$HOME/bin:/usr/local/bin:$PATH
export PATH=/opt/homebrew/opt/php@8.0/bin:$PATH
-----------------------
nano ~/.zshrc
# If you come from bash you might have to change your $PATH.
# export PATH=$HOME/bin:/usr/local/bin:$PATH
export PATH=/opt/homebrew/opt/php@8.0/bin:$PATH
-----------------------
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
      {
        "name": "Launch currently open script",
        "type": "php",
        "request": "launch",
        "program": "${file}",
        "cwd": "${fileDirname}",
        "port": 0,
        "runtimeArgs": [
          "-dxdebug.start_with_request=yes"
        ],
        "runtimeExecutable": "/opt/homebrew/bin/php",
        "env": {
          "XDEBUG_MODE": "debug,develop",
          "XDEBUG_CONFIG": "client_port=${port}"
        }
      },
        {
            "name": "Listen for XDebug",
            "type": "php",
            "request": "launch",
            "port": 9000,
            "runtimeExecutable": "/opt/homebrew/bin/php"
        }
    ]
}

npm run watch/hot only successful on the first run

copy iconCopydownload iconDownload
const mix = require('laravel-mix');
const path = require('path');

const ResolveTypeScriptPlugin = require("resolve-typescript-plugin").default;
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');

mix.webpackConfig({
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: "ts-loader",
                options: {
                    appendTsSuffixTo: [/\.vue$/],
                    transpileOnly: true
                },
                exclude: /node_modules/
            }
        ]
    },
    resolve: {
        extensions: ['.js', '.ts', '.tsx', '.vue'],
        alias: {
            '@': path.resolve(__dirname + '/resources'),
            '@store': path.resolve(__dirname + '/resources/js/store'),
            '@components': path.resolve(__dirname + '/resources/js/components')
        },
        fullySpecified: false,
        plugins: [new ResolveTypeScriptPlugin()]
    },
    plugins: [new ForkTsCheckerWebpackPlugin()],
    devtool: 'source-map'
}).sourceMaps();

mix.ts('resources/js/app.js', 'public/js')
    .sass('resources/sass/app.sass', 'public/css').sourceMaps()
    .vue();

mix.extract();
-----------------------
const path = require('path');

module.exports = {
    resolve: {
        alias: {
            '@': path.resolve('resources/js'),
        },
    },
};
const path = require('path');

module.exports = {
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: "ts-loader",
                options: {
                    appendTsSuffixTo: [/\.vue$/],
                    transpileOnly: true
                },
                exclude: /node_modules/
            }
        ]
    },
    resolve: {
        extensions: ['.js', '.ts', '.tsx', '.vue'],
        alias: {
            '@': path.resolve(__dirname + '/resources/js'),
        },
    },
};
-----------------------
const path = require('path');

module.exports = {
    resolve: {
        alias: {
            '@': path.resolve('resources/js'),
        },
    },
};
const path = require('path');

module.exports = {
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: "ts-loader",
                options: {
                    appendTsSuffixTo: [/\.vue$/],
                    transpileOnly: true
                },
                exclude: /node_modules/
            }
        ]
    },
    resolve: {
        extensions: ['.js', '.ts', '.tsx', '.vue'],
        alias: {
            '@': path.resolve(__dirname + '/resources/js'),
        },
    },
};

How to use parallel testing in multi tenant laravel application?

copy iconCopydownload iconDownload
class ParallelTestingMultiTenantProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        ParallelTesting::setUpTestCase(function ($token, $testCase) {
            $tenant = Tenant::firstOrCreate(['id' => "test_{$token}_tenant", 'name' => "testTenant$token"]);
            $tenant->domains()->firstOrCreate(['domain'=>"testtenant$token.site.test"]);
        });

        ParallelTesting::tearDownProcess(function ($token) {
            try {
                DB::disconnect();
                config(['database.connections.mysql.database'=>"site_test_{$token}"]);
                DB::reconnect();
                if($tenant = Tenant::find("test_{$token}_tenant")){
                    $tenant->delete();
                }
            }
            catch(\Exception $e){
                if($e->getCode() !== 1049){ //Intercepts database does not exist errors - where tests do not use Database traits
                    throw $e;
                }
            }
        });
    }
}

class TenantTestCase extends TestCase
{
    use DatabaseTransactions;

    public function setUp(): void
    {
        parent::setUp();
        if($this->isTestingInParallel()){
            $token = ParallelTesting::token();
            tenancy()->initialize(Tenant::find("test_{$token}_tenant"));
            DB::beginTransaction(); //Needed as otherwise database transactions don't work on the tenant database
            URL::forceRootUrl("https://testtenant$token.site.test");
        }
        else {
            //Test setup for when not running in parallel 
        }
    }

    protected function tearDown(): void
    {
        if($this->isTestingInParallel()){
            DB::rollBack();
        }
        else {
            //Tear down if not testing in parallel
        }
        parent::tearDown();
    }

    protected function isTestingInParallel() : bool
    {
        return (bool)ParallelTesting::token();
    }
}
-----------------------
class ParallelTestingMultiTenantProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        ParallelTesting::setUpTestCase(function ($token, $testCase) {
            $tenant = Tenant::firstOrCreate(['id' => "test_{$token}_tenant", 'name' => "testTenant$token"]);
            $tenant->domains()->firstOrCreate(['domain'=>"testtenant$token.site.test"]);
        });

        ParallelTesting::tearDownProcess(function ($token) {
            try {
                DB::disconnect();
                config(['database.connections.mysql.database'=>"site_test_{$token}"]);
                DB::reconnect();
                if($tenant = Tenant::find("test_{$token}_tenant")){
                    $tenant->delete();
                }
            }
            catch(\Exception $e){
                if($e->getCode() !== 1049){ //Intercepts database does not exist errors - where tests do not use Database traits
                    throw $e;
                }
            }
        });
    }
}

class TenantTestCase extends TestCase
{
    use DatabaseTransactions;

    public function setUp(): void
    {
        parent::setUp();
        if($this->isTestingInParallel()){
            $token = ParallelTesting::token();
            tenancy()->initialize(Tenant::find("test_{$token}_tenant"));
            DB::beginTransaction(); //Needed as otherwise database transactions don't work on the tenant database
            URL::forceRootUrl("https://testtenant$token.site.test");
        }
        else {
            //Test setup for when not running in parallel 
        }
    }

    protected function tearDown(): void
    {
        if($this->isTestingInParallel()){
            DB::rollBack();
        }
        else {
            //Tear down if not testing in parallel
        }
        parent::tearDown();
    }

    protected function isTestingInParallel() : bool
    {
        return (bool)ParallelTesting::token();
    }
}

Why is my custom TestCase class not being found when running tests through PhpUnit?

copy iconCopydownload iconDownload
{
"autoload": {
    "psr-4": {
      "My\\Project\\": "src/"
    }
  },
  "autoload-dev": {
    "psr-4": {
      "My\\Project\\Tests\\": "tests/"
    }
  }
}

Community Discussions

Trending Discussions on phpunit
  • How to test form submission with wrong values using Symfony crawler component and PHPUnit?
  • What is the 'X' in this insert &gt; X'3C2F756C3E'
  • phpunit tests failing after going to php 8.0 because of &quot;Unknown named parameter&quot;
  • Why does class autoloading not work for a package required using &quot;repositories.package&quot;?
  • How to create a double for an interface, usefully, concisely and legally?
  • Unable to get mock container to return anything but null
  • Wrong PHP Version/Executable in VSCode terminal but works perfectly in Mac terminal
  • npm run watch/hot only successful on the first run
  • PHPUnit: how to test HTML structure output
  • Laravel web-Socket installation
Trending Discussions on phpunit

QUESTION

How to test form submission with wrong values using Symfony crawler component and PHPUnit?

Asked 2022-Apr-05 at 11:18

When you're using the app through the browser, you send a bad value, the system checks for errors in the form, and if something goes wrong (it does in this case), it redirects with a default error message written below the incriminated field.

This is the behaviour I am trying to assert with my test case, but I came accross an \InvalidArgumentException I was not expecting.

I am using the symfony/phpunit-bridge with phpunit/phpunit v8.5.23 and symfony/dom-crawler v5.3.7. Here's a sample of what it looks like :

public function testPayloadNotRespectingFieldLimits(): void
{
    $client = static::createClient();

    /** @var SomeRepository $repo */
    $repo = self::getContainer()->get(SomeRepository::class);
    $countEntries = $repo->count([]);
    
    $crawler = $client->request(
        'GET',
        '/route/to/form/add'
    );
    $this->assertResponseIsSuccessful(); // Goes ok.

    $form = $crawler->filter('[type=submit]')->form(); // It does retrieve my form node.
    
    // This is where it's not working.
    $form->setValues([
        'some[name]' => 'Someokvalue',
        'some[color]' => 'SomeNOTOKValue', // It is a ChoiceType with limited values, where 'SomeNOTOKValue' does not belong. This is the line that throws an \InvalidArgumentException.
    )];

    // What I'd like to assert after this
    $client->submit($form);
    $this->assertResponseRedirects();
    $this->assertEquals($countEntries, $repo->count([]));
}

Here's the exception message I get :

InvalidArgumentException: Input "some[color]" cannot take "SomeNOTOKValue" as a value (possible values: "red", "pink", "purple", "white").
vendor/symfony/dom-crawler/Field/ChoiceFormField.php:140
vendor/symfony/dom-crawler/FormFieldRegistry.php:113
vendor/symfony/dom-crawler/Form.php:75

The ColorChoiceType tested here is pretty standard :

public function configureOptions(OptionsResolver $resolver): void
{
    $resolver->setDefaults([
        'choices' => ColorEnumType::getChoices(),
        'multiple' => false,
    )];
}

What I can do, is to wrap in a try-catch block, the line where it sets the wrong value. And it would indeed submit the form and proceed to the next assertion. The issue here is that the form was considered submitted and valid, it forced an appropriate value for the color field (the first choice of the enum set). This is not what I get when I try this in my browser (cf. the intro).

// ...
/** @var SomeRepository $repo */
$repo = self::getContainer()->get(SomeRepository::class);
$countEntries = $repo->count([]); // Gives 0.
// ...
try {
    $form->setValues([
        'some[name]' => 'Someokvalue',
        'some[color]' => 'SomeNOTOKValue',
    ]);
} catch (\InvalidArgumentException $e) {}

$client->submit($form); // Now it submits the form.
$this->assertResponseRedirects(); // Ok.
$this->assertEquals($countEntries, $repo->count([])); // Failed asserting that 1 matches expected 0. !!

How can I mimic the browser behaviour in my test case and make asserts on it ?

ANSWER

Answered 2022-Apr-05 at 11:17

It seems that you can disable validation on the DomCrawler\Form component. Based on the official documentation here.

So doing this, now works as expected :

$form = $crawler->filter('[type=submit]')->form()->disableValidation();
$form->setValues([
    'some[name]' => 'Someokvalue',
    'some[color]' => 'SomeNOTOKValue',
];
$client->submit($form);

$this->assertEquals($entriesBefore, $repo->count([]); // Now passes.

Source https://stackoverflow.com/questions/71565750

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install phpunit

We distribute a PHP Archive (PHAR) that has all required (as well as some optional) dependencies of PHPUnit bundled in a single file:. Please replace X.Y with the version of PHPUnit you are interested in. Alternatively, you may use Composer to download and install PHPUnit as well as its dependencies. Please refer to the "Getting Started" guide for details on how to install PHPUnit.

Support

Please refer to CONTRIBUTING.md for information on how to contribute to PHPUnit and its related projects.

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Explore Related Topics

Share this Page

share link
Reuse Pre-built Kits with phpunit
Consider Popular Unit Testing Libraries
Compare Unit Testing Libraries with Highest Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.