codeception / aspectmock Goto Github PK
View Code? Open in Web Editor NEWThe most powerful and flexible mocking framework for PHPUnit / Codeception.
License: MIT License
The most powerful and flexible mocking framework for PHPUnit / Codeception.
License: MIT License
// mockery
$dice = m::mock('Jasrags\Dice');
var_dump($dice instanceof \Jasrags\Dice);
// PHPUnit
$dice = $this->getMock('Jasrags\Dice');
var_dump($dice instanceof \Jasrags\Dice);
// AspectMock
$dice = test::double(new \Jasrags\Dice);
var_dump($dice instanceof \Jasrags\Dice);
Results:
bool(true)
bool(true)
bool(false)
So I got an error when I use typehinting.
Argument 1 passed to Foo::__construct() must be an instance of Jasrags\Dice, instance of AspectMock\Proxy\InstanceProxy given, called in ...Bar.php on line 55 and defined
I'm trying to find a list of all the paramaters passed into a mocked method but this seems to keep giving me an error. It requires an instance of the class held in the userProxy but when I construct the instance the variables passed in aren't displayed.
save($var) will just echo $var.
$userProxy = test::double('User', ['save' => null]);
$userProxy->save("foo");
var_dump($userProxy->getCallsForMethod('save'));
I added the configuration as suggested in the docs for Yii 1.1 and when I run the unit tests with PHPUnit 3.7, the methods I am mocking do not get overridden.
This is my bootstrap.php for PHPUnit:
<?php
$yiit=dirname(__FILE__).'/../../../yii/framework/yiit.php';
if (!file_exists($yiit))
$yiit = dirname(__FILE__).'/../../vendor/yiisoft/yii/framework/yiit.php';
$config=dirname(__FILE__).'/../config/test.php';
$kernel = AspectMock\Kernel::getInstance();
$kernel->init([
'debug' => true,
'includePaths' => [
__DIR__.'/../',
],
'excludePaths' => [
__DIR__.'/../runtime',
__DIR__.'/../data',
__DIR__.'/../commands',
__DIR__.'/../bin',
__DIR__.'/../migrations',
],
]);
$kernel->loadFile($yiit);
Yii::createWebApplication($config);
?>
//The basic class I am trying to mock:
class FounderBadgeType implements BadgeTypeInterface {
public function getBadgeOrder() {
return 1;
}
//...
}
//Unit Test
$type = test::double(new FounderBadgeType(), ['getBadgeOrder' => 5]);
$this->assertEquals(5,$type->getBadgeOrder()); //FAILS? Still returns 1, not 5
I'm mocking a Laravel Eloquent model and want to check if the 'findOrFail' method is being invoked. I've managed to make a test double and the 'findOrFail' method does indeed return the value that I specify. However, when I check for the method invocation, it fails.
I did some digging and apparently the $calls variable in ClassProxy/getCallsForMethod is being filled with the following attribute (among others):
["__call"]=>
array(1) {
[0]=>
array(2) {
[0]=>
string(10) "findOrFail"
[1]=>
array(1) {
[0]=>
string(1) "1"
}
}
}
So the method invocation is being recorded but obviously the following code which checks for the invocation fails:
return isset($calls[$method])
? $calls[$method]
: [];
The method invocation can be found under $calls['__call']
and not $calls['findOrFail']
Is this something that needs to be fixed or can I go about this some other way?
Regards,
Ivo
See the issue yiisoft/yii#3422
Relevant part of th issue comments:
Here's the output with AspectMock harness enabled:
[vagrant@localhost vagrant]$ phpunit --bootstrap tests/bootstrap.php tests/suites/integration/OrderPaymentHistoryTest.php
PHPUnit 4.5.1 by Sebastian Bergmann and contributors.
Configuration read from /vagrant/phpunit.xml
PHP Parse error: syntax error, unexpected 'as' (T_AS) in /vagrant/common/lib/yii/test/CDbFixtureManager.php on line 171
PHP Stack trace:
<...removed...>
Here's the output without AspectMock:
[vagrant@localhost vagrant]$ phpunit --bootstrap tests/bootstrap-no-aop.php tests/suites/integration/OrderPaymentHistoryTest.php
PHPUnit 4.5.1 by Sebastian Bergmann and contributors.
Configuration read from /vagrant/phpunit.xml
..
Time: 3.58 seconds, Memory: 10.50Mb
OK (2 tests, 2 assertions)
Most important is this:
[vagrant@localhost test]$ php -l CDbFixtureManager.php
No syntax errors detected in CDbFixtureManager.php
CDbFixtureManager.php
is the Yii 1.1 library file for class managing test fixtures. Quite a lot of our old tests use that mechanic and adding AspectMock to our test harness breaks them with aforementioned PHP Parse error. I assume the PHP parser library you're using is broken.
Failure happens at this line:
foreach(require($fileName) as $alias=>$row)
If we extract variable making it
$data = require($fileName)
foreach($data as $alias=>$row)
test start to pass, but the syntax is not wrong either way!
Is there anyway to mock an anonymous function?
Since this testing framework is getting popular lately it would be nice if it worked well with it.
Ex.
Hey. Seems not to work at all. I am running PHP54 and AspectMock 0.4.0
I am trying to mock the following:
$usersCrudManager = new UsersCrudManager();
test::double($usersCrudManager, ['create' => 'test']);
When I am running the test with codeception I am receiving the following:
FATAL ERROR. TESTS NOT FINISHED.
Call to a member function registerObject() on a non-object
in /Users/fightbulc/www/jobs/piraya/service/vendor/codeception/aspect-mock/src/AspectMock/Core/Registry.php:30
I had a look in the code and figured that self::$mocker
isn't set. Setting it via Registry::setMocker(new Mocker());
solves the issue from above. However, it still doesn't mock my class.
Also, I didn't see any examples where Mocker()
needs to be set explicitly.
What needs to be done here, what do I miss?
Cheers
Tino
Go\Instrument\Transformer\FilterInjectorTransformer::rewrite produces Fatal error if $resource parameter is not a string. For example:
$file = new SplFileInfo('example.php');
require_once $file;
This code is valid because SplFileInfo redeclares __toString() method and it returns path to file. This method is widely used in Symfony2:
// \Symfony\Bundle\FrameworkBundle\Test\WebTestCase::getKernelClass
$finder = new Finder();
$finder->name('*Kernel.php')->depth(0)->in($dir);
$results = iterator_to_array($finder);
$file = current($results);
require_once $file;
After updating lisachenko/go-aop-php 2ed1ec1 => 0dd0610, the error occurs.
Strict standards: Declaration of AspectMock\Kernel::registerTransformers() should be compatible with Go\Core\AspectKernel::registerTransformers() in .../vendor/codeception/aspect-mock/src/AspectMock/Kernel.php on line 19
Catchable fatal error: Argument 1 passed to AspectMock\Kernel::registerTransformers() must be an instance of Go\Instrument\ClassLoading\SourceTransformingLoader, none given, called in .../vendor/lisachenko/go-aop-php/src/Go/Core/AspectKernel.php on line 106 and defined in .../vendor/codeception/aspect-mock/src/AspectMock/Kernel.php on line 58
Let's say you have two classes in separate files:
<?php
class GeneratorTest extends GeneratorTestParent {}
<?php
class AOPTestParent {
protected function generator()
{
yield 'foo';
}
}
Then, it is being internally converted to:
<?php
class AOPTestParent {
protected function generator()
{ if (($__am_res = __amock_before($this, __CLASS__, __FUNCTION__, array(), false)) !== __AM_CONTINUE__) return $__am_res;
yield 'foo';
}
}
And any inclusion of AOPTest results in PHP Fatal error: Generators cannot return values using "return"
, since return was added to that method.
I know there're some known issues with Go! and traits for some php54.* versions , but this one is a bit weird (running on php5.5.6).
So basically I have an abstract base class that uses traits and child classes that inherit from this class.
I've split my projects into components, and so there're also configured as different testsuites in the phpunit config xml. When I run my test on the specified testsuite phpunit -c phpunit.xml.dist --testsuite MyComponent
everything's fine. However running the whole testsuite will throw a fatal exception, because it can't find the methods that are inherited from the traits. Without AspectMock, everything works fine again (for both scenarios).
I've also noticed, that this doesn't happen if traits are used directly on a class.
Just wanted to know if that's a known issue. Maybe there's something I've been missing here.
Thanks,
Thomas
When you add a file to be mocked to the includePaths
config the cache isn't updated and you can't mock that class until you manually delete the cache.
A.php
A.php
so it's pulled into the cacheA.php
to your includePaths
configA.php
A.php
won't be mocked because the cache doesn't get refreshedA copy of includePaths
should be included in the cache. When checking if a file should be read from cache or re-processed, we should also check if that file has been added to includePaths
since the cache was last written
I'm not sure this is a bug of AspectMock/Go AOP, or PHP. And it happens on CentOS 6.5 (64bit). Not on Ubuntu 12.04 (32bit), Mac OS X.
I get a strange error that autoloader can't load a class when it is called in a function registered by register_shutdown_function().
I investigated it. I put the code below in shutdown function.
echo file_get_contents('php://filter/read=go.source.transforming.loader/resource=/path/to/class/file.php');
But nothing was outputed.
I put the same code in a test method. It worked fine.
Does anyone have any advices?
Sometimes you have to really mock a function, but sometimes you have run the original behavior.
For example you have a class that stores options like a registry:
$registry = MyFactory::getRegistry();
$registry->get('my.first.option', $default); // To be mocked
$registry->get('second.option', $default2); // Original behavior
There already is something like this? It could be implemented?
Is this something AspectMock could do?
Let's say you have the following class:
class Foo
{
public function bar($first, $second, &$third)
{
echo 'Hello, world!';
}
}
You are expected to create a mock in this way:
$mock = new Foo();
$mock->($first, $second, $third);
However, if you do that, you'll get a PHP Warning, since the $third
argument is not passed by reference.
I'll try to found a workaround for this, if it's possible I'll submit a pull request.
[Sorry, accidently hit "Comment"]
Scenario: I have setup phpunit globally with composer and I'm currently using AspectMock on one project. Thing is, when running unittests on different projects I get this exception:
Fatal error: Class 'Go\Instrument\Transformer\FilterInjectorTransformer' not found in… (path)
What's even more confusing, these lines got injected in the phpunit error handler class
require_once \Go\Instrument\Transformer\FilterInjectorTransformer::rewrite( __DIR__ . '/../Framework/Error.php', __DIR__);
require_once \Go\Instrument\Transformer\FilterInjectorTransformer::rewrite( __DIR__ . '/../Framework/Error/Notice.php', __DIR__);
require_once \Go\Instrument\Transformer\FilterInjectorTransformer::rewrite( __DIR__ . '/../Framework/Error/Warning.php', __DIR__);
require_once \Go\Instrument\Transformer\FilterInjectorTransformer::rewrite( __DIR__ . '/../Framework/Error/Deprecated.php', __DIR__);
I wouldn't expect this behavior. Is there any workaround for this?
Thanks.
First of all thanks for this awesome Mocking library. I've just started playing around with it and it's really useful.
There's something you probably should add to the documentation. If you configure phpunit to backup static attributes, tests will fail with a serialization exception (ref #1).
So alike backupGlobals
, backupStaticAttributes
should be set to false
.
Thanks, Thomas
In \AspectMock\Kernel::init()
the option debug
is always set to true.
Looking at the code, this means that the cache is never read (but it is generated). I commented it out in my local copy, however I was wondering if there is any special reason for this setting
is it possible?
I have one problem with redefining function which already called before in current namespace. Example:
<?php
namespace test;
class Test
{
public function __construct()
{
print time();
}
}
new Test(); // will print timestamp
require 'time.php';
new Test(); // will print timestamp
print time(); // will print 1
new Test(); // will print timestamp
time.php
<?php
namespace test;
function time() {
return 1;
}
And with this situation, a can't mock function in class method which already called in other test cases. Who solved this problem?
I'm trying to test this out, but get "Exception: Serialization of 'Closure' is not allowed" every time I run phpunit. PHPUnit has issues with serializing closures, but I'm not sure why that would affect my machine and not yours.
Here is my source code. I'm not even using any of the functionality yet. Just trying to get the tests to run. See anything glaringly wrong?
https://github.com/JeffreyWay/Temporary-Bug
I'm using PHPUnit 3.7.19 and PHP 5.4.1.
When mocking some class the following code:
foreach (require $file as $key => $value) {
...
}
is returning error "PHP Parse error: syntax error, unexpected 'as' (T_AS)" . It works when not using AspectMock.
Hi,
Just trying out AspeckMock which is great stuff, thanks for the job.
I managed to make it work on my Yii2 project, and can do simple things like:
$market = Test::double('frontend\models\Market');
$language = \frontend\models\Language::findOne('6');
Debug::debug($language->market->name);
Debug::debug($language->market->attributeLabels());
$market->verifyInvokedOnce('attributeLabels'); //True
This works great.
Now, what I'd like to do is to mock a controller to prevent it to call the backend.
Basically I have a method CheckEndpointsController::executeEndpointsCall()
and I'd like it to return my Stub and not execute the call over HTTP.
Here's my code:
class CheckEndpointsCest
{
public function _before(AcceptanceTester $I){ }
public function _after(AcceptanceTester $I) { Test::clean(); }
public function testCheckEndpoints(AcceptanceTester $I)
{
$checkEndpointsController = Test::double('frontend\controllers\CheckEndpointsController');
$checkEndpointsPage = CheckEndpointsPage::openBy($I);
$checkEndpointsPage->selectEnvironment('DEV');
$I->click('#form-submit-button');//This is the moment when it will pass in the method CheckEndpointsController::executeEndpointsCall()
$I->waitForElementVisible('.mtc-resultTable', 30);
$checkEndpointsController->verifyInvoked('executeEndpointsCall'); //False
}
}
My problem is that it doesn't Mock it, at least the verifyInvoked is false when I'm sure it passes by.
First question, is what I'm doing supposed to be possible ? I tend to doubt now, even though I don't see why it wouldn't be.
Second question, what did I do wrong, here is my _bootstrap.php
<?php
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'test');
defined('YII_APP_BASE_PATH') or define('YII_APP_BASE_PATH', dirname(dirname(dirname(__DIR__))));
defined('FRONTEND_ENTRY_URL') or define('FRONTEND_ENTRY_URL', parse_url(\Codeception\Configuration::config()['config']['test_entry_url'], PHP_URL_PATH));
defined('FRONTEND_ENTRY_FILE') or define('FRONTEND_ENTRY_FILE', YII_APP_BASE_PATH . '/frontend/web/index-test.php');
$kernel = \AspectMock\Kernel::getInstance();
$kernel->init([
'debug' => true,
'includePaths' => [
__DIR__ . '/../common',
YII_APP_BASE_PATH . '/frontend'
]
]);
$kernel->loadFile(YII_APP_BASE_PATH . '/vendor/yiisoft/yii2/Yii.php');
require_once(YII_APP_BASE_PATH . '/vendor/autoload.php');
require_once(YII_APP_BASE_PATH . '/vendor/yiisoft/yii2/Yii.php');
require_once(YII_APP_BASE_PATH . '/common/config/bootstrap.php');
require_once(YII_APP_BASE_PATH . '/frontend/config/bootstrap.php');
// set correct script paths
// the entry script file path for functional and acceptance tests
$_SERVER['SCRIPT_FILENAME'] = FRONTEND_ENTRY_FILE;
$_SERVER['SCRIPT_NAME'] = FRONTEND_ENTRY_URL;
$_SERVER['SERVER_NAME'] = parse_url(\Codeception\Configuration::config()['config']['test_entry_url'], PHP_URL_HOST);
$_SERVER['SERVER_PORT'] = parse_url(\Codeception\Configuration::config()['config']['test_entry_url'], PHP_URL_PORT) ?: '80';
Yii::setAlias('@tests', dirname(dirname(__DIR__)));
Thanks for your help.
Cheers,
Nico
Next problem. :)
When I run phpunit
for the following code....
<?php
use AspectMock\Test;
class User {
public function save()
{
return 'saved to db';
}
}
class UserService {
public function create()
{
$user = new User;
$user->save();
}
}
class FirstTest extends PHPUnit_Framework_TestCase {
public function tearDown()
{
Test::clean();
}
public function testIt()
{
$user = Test::double('User', ['save' => null]);
(new UserService)->create();
$user->verifyInvoked('save');
}
}
...I'm told:
1) FirstTest::testIt
Expected User to be invoked but it never occur.
/Users/Jeffrey/Desktop/aspect/vendor/codeception/aspect-mock/src/AspectMock/Core/Verifier.php:59
/Users/Jeffrey/Desktop/aspect/tests/FirstTest.php:34
I thought I was doing it correctly, but maybe not? I updated my test repo with these changes.
You have this dependency in your composer.json file:
"lisachenko/go-aop-php": "~0.4"
This means that go-aop-php will be installed with version >= 0.4 and < 1.0. And since go-aop-php has 0.4.3 as the last stable version, and the development version is 0.5.x and equal to dev-master - AspectMock installs dev-master version. And with this version AspectMock is not working:
PHP Catchable fatal error: Argument 1 passed to AspectMock\Kernel::registerTransformers() must be an instance of Go\Instrument\ClassLoading\SourceTransformingLoader, none given, called in /srv/www/litemf.dev/vendor/lisachenko/go-aop-php/src/Go/Core/AspectKernel.php on line 106 and defined in /srv/www/litemf.dev/vendor/codeception/aspect-mock/src/AspectMock/Kernel.php on line 58
I suggest changing requre string to
"lisachenko/go-aop-php": "~0.4.0"
this will mean >=0.4.0 < 0.5
Hello,
I have setup AspectMock to work with my Laravel application running on Codeception. Using PHP, it works fine, however when using HHVM I get this error.
Warning: File not found:
php://filter/read=go.source.transforming.loader/resource=/liputan6_vagrant/vendor/codeception/aspect-mock/src/AspectMock/Core/Mocker.php in /liputan6_vagrant/vendor/lisachenko/go-aop-php/src/Go/Instrument/ClassLoading/AopComposerLoader.php on line 99
Fatal error: Class undefined: AspectMock\Core\Mocker in /liputan6_vagrant/vendor/codeception/aspect-mock/src/AspectMock/Kernel.php on line 30
Looking through the go-aop-php issues I found this goaop/framework#143 which seems to indicate that for the most part, HHVM support is in place. Might there be a workaround that gets AspectMock working on HHVM as well ?
Hey so I've been playing around with aspect mock and was wondering if there was any way to force a mocked method to throw an error if the method is not called with the correct arguments being passed in? similar to phpunits "expects" method.
One of the classes I'm mocking is called few times along the process and from what I read in the docs, I can only return a single value when defining the mock. Is there a way to change the returning values on each call?
It seems like method invocation via verifyInvoked*()
only works on double instances but not for parent::
method calls. Example:
class ParentClass {
public function hello() {
echo 'Hello';
}
}
class ChildClass extends ParentClass {
public function hello() {
parent::hello();
echo ' World';
}
}
test::double(ParentClass::class, ['hello']);
$c = new ChildClass();
$c->hello();
How would one verify that ParentClass::hello
was invoked?
After updating, cache directories like _annotations
are created in current directory, if 'cacheDir' is not set.
Our company is using Laravel 4 framework, and we have a custom directory within the app
directory which called libraries
.
I can't mock static methods for classes located in libraries directory. I've tried to include this folder with all possible ways explicitly in _bootstrap.php
file (in Codeception). We have Codeception tests located within the app
directory.
The autoload section of our composer.json
looks like this:
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/libraries",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php",
"app/extensions/twig",
"app/facades",
"app/services"
]
},
I've tried to move the class I want to mock to models folder, and I was able to mock it just fine. But when moved to libraries directory again, it is not working anymore.
P. S. I've done composer dumpautoload
, so that shouldn't be the issue of that.
Thanks a lot!
UPD
My _bootstrap.php
file for codeception is:
$kernel = \AspectMock\Kernel::getInstance();
$kernel->init([
'debug' => true,
'cacheDir' => '/tmp/l4-sample',
'includePaths' => [__DIR__.'/../vendor/laravel', __DIR__.'/..', '../libraries'],
'excludePaths' => [__DIR__]
]);
$kernel->loadFile('../../bootstrap/autoload.php');
Hello,
The is no doubt something I am doing wrong, but any help would be greatly appreciated. I get the following error from travis (but not when I run locally):
AspectMock couldn't parse some of files.
Try to exclude them from parsing list.
There were following reasons for this exception:
Function trait_exists was redeclared (previousy declared in file /home/travis/build/bedezign/yii2-audit/vendor/phpunit/phpunit-mock-objects/src/Framework/MockObject/Generator.php).
I have tried excluding the build/
folder (although it's not in the include list) which didnt help. Here is my config:
https://github.com/bedezign/yii2-audit/blob/codeception-tests/tests/codeception/_bootstrap.php
In FuncProxy, the functions verifyInvoked
, verifyInvokedOnce
, verifyNeverInvoked
and verifyInvokedMultipleTimes
all call the parent functions of the same name in Verifier.
These functions have different definitions than the parent functions they are extending, e.g. FuncProxy->verifyInvoked
has arguments $params = null
. But Verifier->verifyInvoked
has arguments $name, $params = null
Isn't this a violation of E_STRICT error standard? I get this error trying to use test::func()
PHPUnit_Framework_Error_Notice : Declaration of AspectMock\Proxy\FuncProxy::verifyInvoked() should be compatible with AspectMock\Proxy\Verifier::verifyInvoked($name, $params = NULL)
The following function cannot be mocked in version 0.5.0:
function getSomething() { return $this->something; }
When AspectMock compiles its version of the class, there is no hook added to the function.
Let's say you have the following function:
public function test_reference($a, &$b, &$c)
{
$foo = 'bar';
}
AspectMock will inject the following string:
if (($__am_res = __amock_before(\$this, __CLASS__, __FUNCTION__, array($a, $b, $c), false)) !== __AM_CONTINUE__) return $__am_res;
As you can see in the mocked function arguments are not passed by reference; this leads to PHP errors while trying to mock this function with a Closure, since your anon function will have arguments passed by reference, but in the mock they aren't defined as such.
However I found a fix for this, a Pull Request will be issued shortly.
Due to #46 I have attempted to disable caching however this currently doesn't work.
If I don't set cacheDir
in the config, or even if I set it to null
it gets overridden here:
// AspectKernel.php
protected function normalizeOptions(array $options)
{
$options = array_replace($this->getDefaultOptions(), $options);
...
$options['cacheDir'] = PathResolver::realpath($options['cacheDir']);
}
When PathResolver::realpath
gets passed null
it returns the current directory. A simple change would be to do this instead:
$options['cacheDir'] = $options['cacheDir'] !== null ? PathResolver::realpath($options['cacheDir']) : null;
Then when we get to the CachingTransformer
$this->cachePath
is always set to something and so it tries to write the cache in an undesired directory:
public function transform(StreamMetaData $metadata)
{
// Do not create a cache
if (!$this->cachePath) { // this is never null
$this->processTransformers($metadata);
return;
}
For example:
test::double('myfunc', function() { return 1; })
$this->assertEquals(1, myfunc());
I tried PHP 5.4 and PHP 5.5.9 (cli) (built: Feb 7 2014 14:31:25)
Both codeception n aspectmock installed using composer
however, the test case just does not get started... any idea?
PHP 5.5 output:
Codeception PHP Testing Framework v1.8.3
Powered by PHPUnit 3.7.32 by Sebastian Bergmann.
Functional Tests (1) -------------------------------------
Time: 164 ms, Memory: 12.50Mb
There was 1 error:
FAILURES!
Tests: 1, Assertions: 0, Errors: 1.
Static methods were introduced in PHP5, but we were allowed to make static calls to non-static methods with the '::' operator and call them as if they were static.
In my scenario, I have code I need to test where it makes a static call to a non-static method. AspectMock seems to behave as I would expect, I can mock the methods and give them return values and it's fine. My problem comes when I need to verify a method is invoked.
It is my observation that verifyInvoked (verifyInvokedOnce, verifyInvokedMultipleTimes) do not seem to keep count of the invocations when there is this kind of mismatch.
Is this intentional or is it a bug/feature request?
Thanks
In the latest commit 22c0f21 all docs are blank.
I'm trying to read from the previous version, but there are parsing errors
I just installed Aspectmock just to figure out that it is not working due to the usage of the short array syntax introduced with PHP 5.4.
I order to make things easier, I think that requirement should be added to composer.json.
Hello guys,
we are working on a very big project, and we decided to adopt AspectMock as our mocking solution. Looks so great for our needs! And it worked wonders, but suddenly we found a really important issue. The mocks are not compatible with type hinting, which is a really useful feature for us. See below:
function addCart(Cart $cart) {}
$cartMock = \AspectMock\Test::double(new Cart, []);
addCart($cartMock); // error, expected $cart to be type Cart
if ($cart instanceof Cart) {
// some valid code that will be never executed
}
Do we have any solution to workaround these problems? Are you planning to do something in order to support this use case? I guess that with pure proxy objects this is not gonna be possible, so you might have to make them to extend from the original mocked class. Would that be feasible with your current architecture?
I didn't wanna say but I would really appreciate a fast reply from you, if it is possible.
I am using the popular framework Laravel and I am trying to mock a class named User that extends Eloquent:
I am trying to mock the create-method that is defined on the abstract class that extends the User class.
test::double('\Illuminate\Database\Eloquent\Model', ['create' => 'create' ]);
\User::create([])->shouldReturn('create'); //still hitting the database
How come this is not working?
Is it possible to mock a static method from the phalcon extension?
$model = test::double("Common\\Models\\User", ["findFirst"=>new User()]);
$user = User::findFirst();
$model->verifyInvoked("findFirst");
I have a model method User::findFirst() I'm trying to mock. User extends Phalcon\Mvc\Model (an extension class) and findFirst is a static method of that parent class. Unfortunately, verifyInvoked() returns false. Is it possible (now OR in the future) that AspectMock could do this? Adding the findFirst method to my User model works, so it appears it is setup correctly.
I'm testing AspectMock on Symfony 2 framework with PHPUnit (tried both 3.7.x and 4.x versions)
I have phpunit loads this bootstrap file
include __DIR__.'/bootstrap.php.cache'; // composer autoload
$kernel = \AspectMock\Kernel::getInstance();
$kernel->init([
'debug' => true,
'includePaths' => [
__DIR__,
__DIR__.'/../src',
__DIR__.'/../vendor'
],
'excludePaths' => [
__DIR__.'/../src/My/Bundle/security-bundle/Tests',
__DIR__.'/../vendor/codeception',
]
]);
All seems fine but this does not work as expected:
$account = test::double('My\AccountBundle\Model\Account', ['getParty' => 'some test party', 'getApproved' => TRUE])->make();
var_dump($account->getParty()); // this returns NULL, expected to be 'some test party'
Hello,
I tryed this following code :
<?php
namespace Stockholders\Tests\Includes;
use Stockholders\Includes\Controller;
use AspectMock\Test as test;
class ControllerTest extends \PHPUnit_Framework_TestCase
{
protected function tearDown()
{
test::clean(); // remove all registered test doubles
}
public function testReturnErrorIfNotValidOrDuplicateCallsMethods()
{
$mock = test::double('\Stockholders\Includes\Controller', [
'returnErrorIfNotValidOrDuplicate' => 'mockedReturnValue'
]);
\Stockholders\Includes\Controller::returnErrorIfNotValidOrDuplicate();
$mock->verifyInvoked('returnErrorIfNotValidOrDuplicate');
}
}
But it always returns "never occur", like this :
1) Stockholders\Tests\Includes\ControllerTest::testReturnErrorIfNotValidOrDuplicateCallsMethods
Expected \Stockholders\Includes\Controller::returnErrorIfNotValidOrDuplicate to be invoked but it never occur.
/var/www/bo/vendor/codeception/aspect-mock/src/AspectMock/Proxy/Verifier.php:64
/var/www/bo/sites/all/modules/stockholder_relationship/Tests/Includes/ControllerTest.php:22
The weird part is that if i die the method calls, it will return 'mockedReturnValue' like he might be.
Any idea ? I'm really stuck since yersteday...
I have User model:
<?php
class User extends Model
{
public static function make($fullname)
{
list($first, $last) = explode(' ', $fullname);
$user = new User;
$user->first_name = $first;
$user->last_name = $last;
$user->save();
}
My test:
$user = test::double('User', ['save' => null]);
User::make('Bob Dylan');
$user->verifyInvokedOnce('save');
$this->assertEquals($user->first_name, 'Bob'); //this does not work
I want to be able to assert that theuser object inside the make function has has certain properties on it. Is this possible?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.