When i execute the plugins/SamplePlugin test cases, it executing perfect except the controller functions which are related to urls.
The test case function like
public function testIndex()
{
$this->get('/sample-plugin /mycontroller/index');
$this->assertResponseOk();
}
when i execute the above testcase the exception
There was 1 error:
1) SamplePlugin\Test\TestCase\Controller\MyControllerTest::test
Index
include(D:\xampp\htdocs\EATZ_V2_3.X\vendor\cakephp\cakephp\tests\test_app\config\routes.php): failed to open stream: No such file or directory
D:\xampp\htdocs\MyApp\vendor\cakephp\cakephp\src\Routing\Router.php:974
D:\xampp\htdocs\MyApp\vendor\cakephp\cakephp\src\Routing\Router.php:974
D:\xampp\htdocs\MyApp\vendor\cakephp\cakephp\src\Routing\Router.php:547
D:\xampp\htdocs\MyApp\vendor\cakephp\cakephp\src\TestSuite\IntegrationTestCase.php:451
D:\xampp\htdocs\MyApp\vendor\cakephp\cakephp\src\TestSuite\IntegrationTestCase.php:392
D:\xampp\htdocs\MyApp\vendor\cakephp\cakephp\src\TestSuite\IntegrationTestCase.php:312
D:\xampp\htdocs\MyApp\vendor\cakephp\cakephp\src\TestSuite\IntegrationTestCase.php:233
D:\xampp\htdocs\MyApp\plugins\SamplePlugin\tests\TestCase\Controller\MyControllerTest.php:29
D:\xampp\php\pear\PHPUnit\TextUI\Command.php:176
D:\xampp\php\pear\PHPUnit\TextUI\Command.php:129
FAILURES!
Tests: 30, Assertions: 42, Errors: 1.
please resove the issue.thanks in advance!!!
The error states that the routes.php file is missing in the folder config. Refer to the CakePHP 3 Documentation to create a meaningful routes.php.
Related
Our current project uses Codeception with the Codeception Allure addon and we are now seeing the following error when we run codecept run acceptance --env chrome --group banana --debug. This error began appearing a few days ago and we are unsure how to correct it. Has anyone ran into this error recently? I have found a number of old posts regarding similar issues but they have all been fixed by the project owners.
[Doctrine\Common\Annotations\AnnotationException]
[Semantical Error] The annotation "#env" in method
LogIntoAdminCest::logIntoAdmin() was never imported. Did you maybe
forget to add a "use" statement for this annotation?
Exception trace:
() at /vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationException.php:54
Doctrine\Common\Annotations\AnnotationException::semanticalError() at /vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php:727
Doctrine\Common\Annotations\DocParser->Annotation() at /vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php:663
Doctrine\Common\Annotations\DocParser->Annotations() at /vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php:354
Doctrine\Common\Annotations\DocParser->parse() at /vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationReader.php:284
Doctrine\Common\Annotations\AnnotationReader->getMethodAnnotations() at /vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/IndexedReader.php:71
Doctrine\Common\Annotations\IndexedReader->getMethodAnnotations() at /vendor/allure-framework/allure-php-api/src/Yandex/Allure/Adapter/Annotation/AnnotationProvider.php:43
Yandex\Allure\Adapter\Annotation\AnnotationProvider::getMethodAnnotations() at /vendor/allure-framework/allure-codeception/src/Yandex/Allure/Adapter/AllureAdapter.php:250
Yandex\Allure\Adapter\AllureAdapter->testStart() at n/a:n/a
call_user_func() at /vendor/symfony/event-dispatcher/EventDispatcher.php:212
Symfony\Component\EventDispatcher\EventDispatcher->doDispatch() at /vendor/symfony/event-dispatcher/EventDispatcher.php:44
Symfony\Component\EventDispatcher\EventDispatcher->dispatch() at /vendor/codeception/codeception/src/Codeception/PHPUnit/Listener.php:90
Codeception\PHPUnit\Listener->startTest() at /vendor/phpunit/phpunit/src/Framework/TestResult.php:386
PHPUnit_Framework_TestResult->startTest() at /vendor/codeception/codeception/src/Codeception/Test/Test.php:74
Codeception\Test\Test->run() at /vendor/phpunit/phpunit/src/Framework/TestSuite.php:722
PHPUnit_Framework_TestSuite->run() at /vendor/codeception/codeception/src/Codeception/PHPUnit/Runner.php:106
Codeception\PHPUnit\Runner->doEnhancedRun() at /vendor/codeception/codeception/src/Codeception/SuiteManager.php:157
Codeception\SuiteManager->run() at /vendor/codeception/codeception/src/Codeception/Codecept.php:184
Codeception\Codecept->runSuite() at /vendor/codeception/codeception/src/Codeception/Codecept.php:175
Codeception\Codecept->run() at /vendor/codeception/codeception/src/Codeception/Command/Run.php:376
Codeception\Command\Run->runSuites() at /vendor/codeception/codeception/src/Codeception/Command/Run.php:303
Codeception\Command\Run->execute() at /vendor/symfony/console/Command/Command.php:264
Symfony\Component\Console\Command\Command->run() at /vendor/symfony/console/Application.php:874
Symfony\Component\Console\Application->doRunCommand() at /vendor/symfony/console/Application.php:228
Symfony\Component\Console\Application->doRun() at /vendor/symfony/console/Application.php:130
Symfony\Component\Console\Application->run() at /vendor/codeception/codeception/src/Codeception/Application.php:103
Codeception\Application->run() at /vendor/codeception/codeception/codecept:36
run [-o|--override OVERRIDE] [-e|--ext EXT] [--report] [--html [HTML]] [--xml [XML]] [--tap [TAP]] [--json [JSON]] [--colors] [--no-colors] [--silent] [--steps] [-d|--debug] [--coverage [COVERAGE]] [--coverage-html [COVERAGE-HTML]] [--coverage-xml [COVERAGE-XML]] [--coverage-text [COVERAGE-TEXT]] [--coverage-crap4j [COVERAGE-CRAP4J]] [--no-exit] [-g|--group GROUP] [-s|--skip SKIP] [-x|--skip-group SKIP-GROUP] [--env ENV] [-f|--fail-fast] [--no-rebuild] [--] [<suite>] [<test>]
I have a Grails 2.5.0 app running and this test:
package moduleextractor
import grails.test.mixin.TestFor
import spock.lang.Specification
/**
* See the API for {#link grails.test.mixin.web.ControllerUnitTestMixin} for usage instructions
*/
#TestFor(ExtractorController)
class ExtractorControllerSpec extends Specification {
def moduleDataService
def mockFile
def setup() {
moduleDataService = Mock(ModuleDataService)
mockFile = Mock(File)
}
def cleanup() {
}
void "calls the moduleDataService"() {
given: 'a term is passed'
params.termCode = termCode
when: 'the getModuleData action is called'
controller.getModuleData()
then: 'the service is called 1 time'
1 * moduleDataService.getDataFile(termCode, 'json') >> mockFile
where:
termCode = "201415"
}
}
If I run grails test-app unit:spock I get this:
| Tests PASSED - view reports in /home/foo/Projects/moduleExtractor/target/test-reports
I don't understand why it sees 2 tests. I have not included spock in my BuildConfig file as it is already included in Grails 2.5.0. Also the test is not supposed to pass, as I do not have a service yet. Why does it pass?
Also when I run this grails test-app ExtractorController I get another result:
| Running 2 unit tests...
| Running 2 unit tests... 1 of 2
| Failure: calls the moduleDataService(moduleextractor.ExtractorControllerSpec)
| Too few invocations for:
1 * moduleDataService.getDataFile(termCode, 'json') >> mockFile (0 invocations)
Unmatched invocations (ordered by similarity):
None
at org.spockframework.mock.runtime.InteractionScope.verifyInteractions(InteractionScope.java:78)
at org.spockframework.mock.runtime.MockController.leaveScope(MockController.java:76)
at moduleextractor.ExtractorControllerSpec.calls the moduleDataService(ExtractorControllerSpec.groovy:27)
| Completed 1 unit test, 1 failed in 0m 3s
| Tests FAILED - view reports in /home/foo/Projects/moduleExtractor/target/test-reports
| Error Forked Grails VM exited with error
If I run grails test-app unit: I get:
| Running 4 unit tests...
| Running 4 unit tests... 1 of 4
| Failure: calls the moduleDataService(moduleextractor.ExtractorControllerSpec)
| Too few invocations for:
1 * moduleDataService.getDataFile(termCode, 'json') >> mockFile (0 invocations)
Unmatched invocations (ordered by similarity):
None
at org.spockframework.mock.runtime.InteractionScope.verifyInteractions(InteractionScope.java:78)
at org.spockframework.mock.runtime.MockController.leaveScope(MockController.java:76)
at moduleextractor.ExtractorControllerSpec.calls the moduleDataService(ExtractorControllerSpec.groovy:27)
| Completed 1 unit test, 1 failed in 0m 3s
| Tests FAILED - view reports in /home/foo/Projects/moduleExtractor/target/test-reports
| Error Forked Grails VM exited with error
First of all could somebody tell me what is the correct syntax to run spock tests?
Also what is the difference between having unit and unit: and unit:spock in the command?
(Since Spock comes with Grails 2.5.0, it will run spocks tests anyway.)
What is the correct syntax and why does it sees 2 tests instead of 1 ?
Don't be concerned with the number of tests. It's never been a problem for me. You can always check the report HTML file to see exactly what ran.
I always run my tests with either
grails test-app
or
grails test-app ExtractorController
The error you're getting means you coded the test to expect moduleDataService.getDataFile() to get called with parameters null and 'json' when controller.getModuleData() is called. However, moduleDataService.getDataFile() never got called, so the test failed.
Spock takes some getting used to. I recommend looking at examples in the Grails documentation and reading the Spock Framework Reference.
First question: for the 'grails test-app unit:spock', have you looked at the results to see the tests it says passed? The test count at the CLI can be wrong, check your results to see what actually ran (if no tests actually ran, then there were no failures).
Your test method doesn't start with 'test', nor does it have a #Test annotation, so the 'void "calls the moduleDataService"' isn't being seen as a spock test case (I believe that is the reason).
When you run 'grails test-app ExtractorController', you aren't specifying that it has to be a spock test, so grails testing finds and executes the 'calls the moduleDataService' test method.
Since spock is the de facto testing framework, you can just use:
grails test-app -unit
Second question:
#TestFor creates your controller, but if you're running a unit test, then the usual grails magic isn't happening. Your controller code is executing in isolation. If your ExtractorController usually has the moduleDataService injected, you'll have to take care of that.
I work in grails 2.4.3, and here would be my interpretation of your test (assuredly in need of tweaking since I'm inferring a lot in this example):
import grails.test.mixin.TestFor
import grails.test.mixin.Mock
import spock.lang.specification
import some.pkg.ModuleDataService // if necessary
import some.pkg.File // if necessary
#TestFor(ExtractorController)
#Mock([ModuleDataService, File])
class ExtractorControllerSpec extends Specification
def "test callsModuleDataService once for a termCode"() {
setup:
def mockFile = mockFor(File)
def mockService = mockFor(ModuleDataService, true) // loose mock
// in this mockService, we expect getDataFile to be called
// just once, with two parameters, and it'll return a mocked
// file
mockService.demand.getDataFile(1) { String termCode, String fmt ->
return mockFile.createMock()
}
controller.moduleDataService = mockService.createMock()
when:
controller.params.termCode = "201415"
controller.getModuleData()
then:
response.status == 200 // all good?
}
}
Last question: is that a Banner term code? (just curious)
I am just starting to learn Grails testing and I tried to write my first grails test.For this, I created a fresh grails project and created a controller named com.rahulserver.SomeController:
package com.rahulserver
class SomeController {
def index() { }
def someAction(){
}
}
When I created this controller, grails automatically created a com.rahulserver.SomeControllerSpec under test/unit folder.
Here is my SomeControllerSpec.groovy:
package com.rahulserver
import grails.test.mixin.TestFor
import spock.lang.Specification
/**
* See the API for {#link grails.test.mixin.web.ControllerUnitTestMixin} for usage instructions
*/
#TestFor(SomeController)
class SomeControllerSpec extends Specification {
def setup() {
}
def cleanup() {
}
void testSomeAction() {
assert 1==1
}
}
When I right click this class, and run this test, I get following:
Testing started at 5:21 PM ...
|Loading Grails 2.4.3
|Configuring classpath
.
|Environment set to test
....................................
|Running without daemon...
..........................................
|Compiling 1 source files
.
|Running 1 unit test...|Running 1 unit test... 1 of 1
--Output from initializationError--
Failure: |
initializationError(org.junit.runner.manipulation.Filter)
|
java.lang.Exception: No tests found matching grails test target pattern filter from org.junit.runner.Request$1#1f0f9da5
at org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:35)
at org.junit.runner.JUnitCore.run(JUnitCore.java:138)
No tests found matching grails test target pattern filter from org.junit.runner.Request$1#1f0f9da5
java.lang.Exception: No tests found matching grails test target pattern filter from org.junit.runner.Request$1#1f0f9da5
at org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:35)
at org.junit.runner.JUnitCore.run(JUnitCore.java:138)
|Completed 1 unit test, 1 failed in 0m 0s
.Tests FAILED
|
- view reports in D:\115Labs\grailsunittestdemo\target\test-reports
Error |
Forked Grails VM exited with error
Process finished with exit code 1
So why is it failing?
EDIT
I am using grails 2.4.3
The unit tests are defined with Spock by default:
void testSomeAction() {
assert 1==1
}
Should be written as:
void "Test some action"() {
expect:
1==1
}
See http://spockframework.github.io/spock/docs/1.0/index.html
I want to disable the DB writing when functional testing a controller in phpunit.
In a project in Symfony2, I use phpunit to test a POST call to an API endpoint that saves to database. This worked and I now have a regression problem when activating FOSUser + HWIOAuth.
To avoid the phpunit writing dummy data to the database, I use this trick here: Testing Controllers in Symfony2 with Doctrine to mock the entity manager, then inject the mocked service into the container of the testing system.
This way when you run the test, the DB endpoint is mocked and it is only tested that a flush() is called thanks to the $entityManagerMock->expects($this->once())->method('flush'); that you can see in that question and in the code below.
This used to work.
This test gave green bar, POST calls were tested and no data was saved to the database.
public function testPostCreatesIssue()
{
$client = static::createClient();
$entityManagerMock = $this->getMockBuilder( 'Doctrine\ORM\EntityManager' )
->setMethods( array( 'persist', 'flush' ) )
->disableOriginalConstructor()
->getMock();
$entityManagerMock->expects( $this->once() )
->method( 'flush' );
$client->getContainer()->set( 'doctrine.orm.default_entity_manager', $entityManagerMock );
$postData = array
(
'title' => 'Issues controller test, post creates issue',
'body' => 'The test tests that a post call' . PHP_EOL . 'creates a new issue' . PHP_EOL . 'in the database.' . PHP_EOL . 'UTF8: áéíóú àèìòù ñç',
'pageUrl' => 'file://Xmontero/AntiqueCrayon/MainBundle/Tests/Controller/IssuesControllerTest.php'
);
$crawler = $client->request( 'POST', '/issues/', $postData );
$response = $client->getResponse();
$this->assertEquals( Response::HTTP_CREATED, $response->getStatusCode() );
$this->assertEquals( 'application/json', $response->headers->get( 'content-type' ) );
}
At that moment, I only had the default bundles + my own bundles in the AppKernel.php
The problem
When I activate those bundles in the AppKernel.php
new FOS\UserBundle\FOSUserBundle(),
new HWI\Bundle\OAuthBundle\HWIOAuthBundle(),
and after configuration, everything works properly testing manually in my browser, including the ajax call that does the POST tested above. That controller has nothing to do with the FOSUser and HWIOAuth as that controller worked before I activated those bundles in the kernel.
But despite the manual test did work, the automated test started to fail giving Call to a member function getRepository() on a non-object not in a line of my code but in the very internals of the FOS and the Doctrine - here's the full output:
xavi#bromo:/files/custom_www/antique-crayon/preproduction$ phpunit -c app --filter Post src/Xmontero/AntiqueCrayon/MainBundle/Tests/Controller/IssuesControllerTest.php
PHPUnit 3.6.10 by Sebastian Bergmann.
Configuration read from /files/custom_www/antique-crayon/preproduction/app/phpunit.xml.dist
PHP Fatal error: Call to a member function getRepository() on a non-object in /files/custom_www/antique-crayon/preproduction/vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php on line 759
PHP Stack trace:
PHP 1. {main}() /usr/bin/phpunit:0
PHP 2. PHPUnit_TextUI_Command::main() /usr/bin/phpunit:46
PHP 3. PHPUnit_TextUI_Command->run() /usr/share/php/PHPUnit/TextUI/Command.php:130
PHP 4. PHPUnit_TextUI_TestRunner->doRun() /usr/share/php/PHPUnit/TextUI/Command.php:192
PHP 5. PHPUnit_Framework_TestSuite->run() /usr/share/php/PHPUnit/TextUI/TestRunner.php:325
PHP 6. PHPUnit_Framework_TestSuite->runTest() /usr/share/php/PHPUnit/Framework/TestSuite.php:745
PHP 7. PHPUnit_Framework_TestCase->run() /usr/share/php/PHPUnit/Framework/TestSuite.php:772
PHP 8. PHPUnit_Framework_TestResult->run() /usr/share/php/PHPUnit/Framework/TestCase.php:751
PHP 9. PHPUnit_Framework_TestCase->runBare() /usr/share/php/PHPUnit/Framework/TestResult.php:649
PHP 10. PHPUnit_Framework_TestCase->runTest() /usr/share/php/PHPUnit/Framework/TestCase.php:804
PHP 11. ReflectionMethod->invokeArgs() /usr/share/php/PHPUnit/Framework/TestCase.php:942
PHP 12. Xmontero\AntiqueCrayon\MainBundle\Tests\Controller\IssuesControllerTest->testPostCreatesIssue() /files/custom_www/antique-crayon/preproduction/src/Xmontero/AntiqueCrayon/MainBundle/Tests/Controller/IssuesControllerTest.php:0
PHP 13. Symfony\Component\BrowserKit\Client->request() /files/custom_www/antique-crayon/preproduction/src/Xmontero/AntiqueCrayon/MainBundle/Tests/Controller/IssuesControllerTest.php:41
PHP 14. Symfony\Bundle\FrameworkBundle\Client->doRequest() /files/custom_www/antique-crayon/preproduction/vendor/symfony/symfony/src/Symfony/Component/BrowserKit/Client.php:327
PHP 15. Symfony\Component\HttpKernel\Client->doRequest() /files/custom_www/antique-crayon/preproduction/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Client.php:111
PHP 16. Symfony\Component\HttpKernel\Kernel->handle() /files/custom_www/antique-crayon/preproduction/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Client.php:81
PHP 17. Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel->handle() /files/custom_www/antique-crayon/preproduction/app/bootstrap.php.cache:2330
PHP 18. Symfony\Component\HttpKernel\HttpKernel->handle() /files/custom_www/antique-crayon/preproduction/app/bootstrap.php.cache:3080
PHP 19. Symfony\Component\HttpKernel\HttpKernel->handleRaw() /files/custom_www/antique-crayon/preproduction/app/bootstrap.php.cache:2931
PHP 20. Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher->dispatch() /files/custom_www/antique-crayon/preproduction/app/bootstrap.php.cache:2958
PHP 21. Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcher->preProcess() /files/custom_www/antique-crayon/preproduction/vendor/symfony/symfony/src/Symfony/Component/EventDispatcher/Debug/TraceableEventDispatcher.php:107
PHP 22. Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher->getListeners() /files/custom_www/antique-crayon/preproduction/vendor/symfony/symfony/src/Symfony/Component/EventDispatcher/Debug/TraceableEventDispatcher.php:215
PHP 23. Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher->lazyLoad() /files/custom_www/antique-crayon/preproduction/vendor/symfony/symfony/src/Symfony/Component/EventDispatcher/ContainerAwareEventDispatcher.php:128
PHP 24. Symfony\Component\DependencyInjection\Container->get() /files/custom_www/antique-crayon/preproduction/vendor/symfony/symfony/src/Symfony/Component/EventDispatcher/ContainerAwareEventDispatcher.php:188
PHP 25. appTestDebugProjectContainer->getProfilerListenerService() /files/custom_www/antique-crayon/preproduction/app/bootstrap.php.cache:2056
PHP 26. Symfony\Component\DependencyInjection\Container->get() /files/custom_www/antique-crayon/preproduction/app/cache/test/appTestDebugProjectContainer.php:2251
PHP 27. appTestDebugProjectContainer->getProfilerService() /files/custom_www/antique-crayon/preproduction/app/bootstrap.php.cache:2056
PHP 28. Symfony\Component\DependencyInjection\Container->get() /files/custom_www/antique-crayon/preproduction/app/cache/test/appTestDebugProjectContainer.php:2234
PHP 29. appTestDebugProjectContainer->getSecurity_ContextService() /files/custom_www/antique-crayon/preproduction/app/bootstrap.php.cache:2056
PHP 30. Symfony\Component\DependencyInjection\Container->get() /files/custom_www/antique-crayon/preproduction/app/cache/test/appTestDebugProjectContainer.php:2374
PHP 31. appTestDebugProjectContainer->getSecurity_Authentication_ManagerService() /files/custom_www/antique-crayon/preproduction/app/bootstrap.php.cache:2056
PHP 32. Symfony\Component\DependencyInjection\Container->get() /files/custom_www/antique-crayon/preproduction/app/cache/test/appTestDebugProjectContainer.php:3941
PHP 33. appTestDebugProjectContainer->getFosUser_UserProvider_UsernameEmailService() /files/custom_www/antique-crayon/preproduction/app/bootstrap.php.cache:2056
PHP 34. Symfony\Component\DependencyInjection\Container->get() /files/custom_www/antique-crayon/preproduction/app/cache/test/appTestDebugProjectContainer.php:3885
PHP 35. appTestDebugProjectContainer->getFosUser_UserManagerService() /files/custom_www/antique-crayon/preproduction/app/bootstrap.php.cache:2056
PHP 36. FOS\UserBundle\Doctrine\UserManager->__construct() /files/custom_www/antique-crayon/preproduction/app/cache/test/appTestDebugProjectContainer.php:1657
PHP 37. Doctrine\ORM\EntityManager->getRepository() /files/custom_www/antique-crayon/preproduction/vendor/friendsofsymfony/user-bundle/FOS/UserBundle/Doctrine/UserManager.php:40
xavi#bromo:/files/custom_www/antique-crayon/preproduction$
Narrowing down the problem
The problem is the service doctrine.orm.default_entity_manager for which I inject a mock during the test phase, this is why the manual test in the browser does not fail: No mocks, there.
If I edit my test to do not use any mock, just write to the real DB, it then works:
To test without mock I just comment out the ->set() in the container. And to avoid an Method was expected to be called 1 times, actually called 0 times. I also comment out the ->expects():
//$entityManagerMock->expects( $this->once() )
// ->method( 'flush' );
//
//$client->getContainer()->set( 'doctrine.orm.default_entity_manager', $entityManagerMock );
then the tests greenbars:
xavi#bromo:/files/custom_www/antique-crayon/preproduction$ phpunit -c app --filter Post src/Xmontero/AntiqueCrayon/MainBundle/Tests/Controller/IssuesControllerTest.php
PHPUnit 3.6.10 by Sebastian Bergmann.
Configuration read from /files/custom_www/antique-crayon/preproduction/app/phpunit.xml.dist
.
Time: 0 seconds, Memory: 32.50Mb
OK (1 test, 2 assertions)
xavi#bromo:/files/custom_www/antique-crayon/preproduction$
Conclusions
Injecting a mock in doctrine.orm.default_entity_manager pre-activating FOSUser and HWIOAuth, works fine
When activating these bundles in the AppKernel the trick does not work.
I then only can test allowing to write real data to a database, which is not desired when testing.
Question
How can I disable the writing to the DataBase when calling a controller from a test in phpunit, when FOSUserBundle and HWIOAuthBundle are activated in the kernel?
Thanks!
Xavi.
I'm not proud about it but I haven't done so many test with phpUnit to answer your question with a 100% of security on the answer, but here is my opinion.
I think that the solution is to mock the entityManager, as you are doing yet, but you are moking only the persist() and flush() method.
->setMethods( array( 'persist', 'flush' ) )
->disableOriginalConstructor()
Without the code you are trying to test I can't know it for sure, but it seems that in any part of your controller you're using de FOSUserBundle or the HWIOAuthBundle and one or both of them is using at least the getRepository() method and you need to mock at least all the methods that can be used via FOSUserBundle and HWIOAuthBundle.
If you don't indicate the methods with the setMethods() all of them are mocked, and you can still have controll with the number of times a method is called or not as in the code example below.
$mockObjectManager = $this->getMockBuilder('Doctrine\ORM\EntityManager')
->disableOriginalConstructor()
->getMock();
$mockObjectManager->expects($this->any())
->method('persist');
$mockObjectManager->expects($this->atLeastOnce())
->method('flush');
If the FOSUserBundle is trying to get the repository, as it seems, you will have to mock the return of that call, if you don't do that it will probably end with an error at the next call, an example:
$this->em->expects($this->any())
->method('getRepository')
->with('FOSUserBundle:XXXXX')
->will($this->returnValue($this->getMockedClassWithFind('\Doctrine\ORM\EntityRepository')));
I think the best solution is to start resolving this first error, you will see another error because the object the FosUserBundle is expecting will be null, and mock that one, and maybe expects another object or maybe you're done.
Hope is helpful.
I am trying to configure Magento test automation framework on my system.
When I run phpunit in command line, I am getting following error. Same error I am getting while running test in the netbeans.
Strict Standards: Declaration of Mage_Selenium_Driver::doCommand() should
be compatible with that of PHPUnit_Extensions_SeleniumTestCase_Driver::doCommand()
in C:\MTAF\taf\lib\Mage\Selenium\Driver.php on line 38
..
Fatal error: Call to undefined method PHPUnit_Framework_TestSuite::isPublicTestMethod() in C:\MTAF\taf\lib\Mage\Selenium\TestCase.php on line 2502
Can some one please suggest some solution for the same.
I changed the code, this is the change I performed:
--- a/framework/Mage/Selenium/TestCase.php
+++ b/framework/Mage/Selenium/TestCase.php
## -409,7 +409,7 ## class Mage_Selenium_TestCase extends PHPUnit_Extensions_SeleniumTestCase
$testMethods = array();
$class = new ReflectionClass(self::$_testClass);
foreach ($class->getMethods() as $method) {
- if (PHPUnit_Framework_TestSuite::isPublicTestMethod($method)) {
+ if ($method->isPublic()) {
$testMethods[] = $method->getName();
}
}
I was getting this error when running phpunit >= 4.0. Downgrading to 3.7.x solved it for me.