interface,phpunit,typo3,implementation,extbase , PHP-Unit Tests: how to implement a TYPO3 Extbase object interface


PHP-Unit Tests: how to implement a TYPO3 Extbase object interface

Question:

Tag: interface,phpunit,typo3,implementation,extbase

I have some problems with the PHP UnitTests for my Controller:

this is the function in my controller code that has to be tested

public function newAction(\ReRe\Rere\Domain\Model\Fach $newFach = NULL) {
    // Holt die übergebene Modulnummer
    if ($this->request->hasArgument('modul')) {
        // Holt das Modul-Objekt aus dem Repository
        $modul = $this->modulRepository->findByUid($this->request->getArgument('modul'));
    }
    // Ausgabe in der View
    $this->view->assignMultiple(array(
        'newFach' => $newFach, self::MODULUID => $modul->getUid(), 'modulname' => $modul->getModulname(), 'modulnummer' => $modul->getModulnr(), 'gueltigkeitszeitraum' => $modul->getGueltigkeitszeitraum()
    ));
}

this is the PHPUnit-Test code for the function

public function newActionAssignsTheGivenFachToView() {
    $fach = new \ReRe\Rere\Domain\Model\Fach();
    $modul = array('');

    $MockGetArgument = $this->getMock('ReRe\Rere\Domain\Repository\ModulRepository', array('getArgument'), array(), '', FALSE);
    $MockGetArgument->expects($this->any())->method('getArgument')->with('modul');

    $mockRequest = $this->getMock('TYPO3\\CMS\\Extbase\\Mvc\\Request');
    $mockRequest->expects($this->any())->method('hasArgument')->with('modul');
    $this->inject($this->subject, 'request', $mockRequest);

    $objectManager = $this->getMock('TYPO3\\CMS\\Extbase\\Persistence\\ObjectManager', array(), array(), '', FALSE);
    $this->inject($this->subject, 'objectManager', $objectManager);

    $modulRepository = $this->getMock('ReRe\\Rere\\Domain\\Repository\\ModulRepository');
    $modulRepository->expects($this->any())->method('findByUid')->will($this->returnValue($modul));
    $this->inject($this->subject, 'modulRepository', $modulRepository);

    $view = $this->getMock(self::VIEWINTERFACE);
    $view->expects($this->any())->method(self::ASSIGN)->with('newFach', $fach);
    $this->inject($this->subject, 'view', $view);

    $this->subject->newAction($fach);
}

I keep getting this error as I run the test

Error in test case newActionAssignsTheGivenFachToView File: /Applications/MAMP/typo3_src/typo3/sysext/extbase/Classes/Mvc/Controller/AbstractController.php Line: 162 Argument 1 passed to TYPO3\CMS\Extbase\Mvc\Controller\AbstractController::injectObjectManager() must implement interface TYPO3\CMS\Extbase\Object\ObjectManagerInterface, instance of Mock_ObjectManager_fa2fde18 given, called in /Applications/MAMP/typo3_src/typo3/sysext/core/Tests/BaseTestCase.php on line 260 and defined

And this is the line from AbstractController.php that was called

public function injectObjectManager(\TYPO3\CMS\Extbase\Object\ObjectManagerInterface $ObjectManager) {
    $this->ObjectManager = $ObjectManager;
    $this->arguments = $this->ObjectManager->get('TYPO3\\CMS\\Extbase\\Mvc\\Controller\\Arguments');
}

How can I implement this interface TYPO3\CMS\Extbase\Object\ObjectManagerInterface ?

I really appreciate every answers ! I have been trying and looking for answers for weeks :(

UPDATE 18.02.2015: PROBLEM SOLVED

CONFIGURED CODE:

$fach = new \ReRe\Rere\Domain\Model\Fach();
        $modul = new \ReRe\Rere\Domain\Model\Modul();

        $request = $this->getMock(self::REQUEST, array(), array(), '', FALSE);
        $request->expects($this->once())->method('hasArgument')->will($this->returnValue($this->subject));

        $modulRepository = $this->getMock(self::MODULREPOSITORY, array('findByUid'), array(), '', FALSE);
        $modulRepository->expects($this->once())->method('findByUid')->will($this->returnValue($modul));
        $this->inject($this->subject, 'modulRepository', $modulRepository);

        $request->expects($this->once())->method('getArgument')->will($this->returnValue($this->subject));
        $this->inject($this->subject, 'request', $request);

        $view = $this->getMock(self::VIEWINTERFACE);
        $view->expects($this->once())->method('assignMultiple')->with(array(
            'newFach' => $fach,
            'moduluid' => $modul->getUid(),
            'modulname' => $modul->getModulname(),
            'modulnummer' => $modul->getModulnr(),
            'gueltigkeitszeitraum' => $modul->getGueltigkeitszeitraum()
        ));
        $this->inject($this->subject, 'view', $view);

        $this->subject->newAction($fach);


Answer:

You are mocking the wrong (inexistent) ObjectManager. The correct namespace is TYPO3\\CMS\\Extbase\\Object\\ObjectManager.

So the correct line should be $objectManager = $this->getMock('TYPO3\\CMS\\Extbase\\Object\\ObjectManager', ...);

Otherwise I wonder why you mock the ObjectManager at all. You don't use it in your method.

One side note: Your code will fail if there is no 'modul' inside the request. Then $modul is not set and you will call getUid(), getModulname(), ... on an non-object.


Related:


How can I make PHPUnit ignore a file pattern?


php,zend-framework2,phpunit
I'm doing Code Coverage reports for a project and there's a ton of files that are included or required while tests are running that are not actually required to be tested or added to coverage reports (I'm using Zend Framework 2; config + Module files are the culprit here). Is...

PhpStorm : Error in argument 1, char 2: option not found S


php,phpunit,phpstorm
So PHPstorm is running the PHP code fine in its console when I click run; that's great but I want to see it in the browser. So, I created a Built in Server inside project. Now, when I clicked on Run -> Run Project, I'm getting error as: "Error in...

Controller with same structure not working using an interface


c#,asp.net-mvc,interface,datacontext
I have created 8 models and controllers respectively for my Project using the same structure, however now this structure is not working. It is giving me this error: The current type, HelpDesk.Contracts.Repositories.IRepositoryBase`1[HelpDesk.Model.Knowledgebase], is an interface and cannot be constructed. Are you missing a type mapping? Here is my interface: namespace...

Travis CI is not case-sensitive by default?


filesystems,phpunit,composer-php,travis-ci,case-sensitive
I have a php project that has composer dependencies which are inherently tested in the code path of my unit tests. Here's my sample code: <?php // where FooBar is a composer package but I'm purposely typing it incorrectly here use \fooBaR public function appendNameToWords(array $words, $name) { $start =...

Cakephp 3 - MissingDatasourceConfigException when running phpunit test


php,unit-testing,cakephp,phpunit,cakephp-3.0
I am trying to run some unit tests in CakePHP 3 with PHPUnit 4.7.3, but I`m getting the following error: PHPUnit 4.7.3 by Sebastian Bergmann and contributors. There was 1 error: 1) App\Test\TestCase\Model\Table\MoviesTableTest::testFindMoviesByGenre Cake\Datasource\Exception\MissingDatasourceConfigException: The datasource configuration "default" was not found. C:\xampp\htdocs\movie-pal\vendor\cakephp\cakephp\src\Datasource\ConnectionManager.php:188 C:\xampp\htdocs\movie-pal\vendor\cakephp\cakephp\src\ORM\TableRegistry.php:191...

What are the advantages of explicit interface implementation in C#? [duplicate]


c#,inheritance,interface,implementation
This question already has an answer here: C# Interfaces. Implicit implementation versus Explicit implementation 11 answers C# supports built-in mechanism for differentiating methods that have the same names. Here is a simple example below shows how it works: interface IVehicle{ //identify vehicle by model, make, year void IdentifySelf(); }...

Symfony Crawler: how to check that a link to a particular page exists


php,symfony2,phpunit,functional-testing
I'm writing some functional tests and i want to verify that the Edit link exists on the page if the user is logged in. The link is a simple <a href="/profile/22/edit">Edit</a>. How can I filter it using the Crawler component of Symfony? One solution is this: $this->assertEquals(1, $crawler->filter('html:contains("<a href="/profile/22/edit">")')->count()); But...

Java: Abstract classes methods and interface


java,interface,abstract
The program below calculates the total of the areas of any number of shapes instantiated. The problem is that I don't know how to output the draw() method of the interface. Here is the main class: public class MyClass1{ public static void main(String[] args) { Shape[] shapes= new Shape[3]; shapes[0]=...

phpunit and http content-type


rest,laravel,phpunit,dingo-api
I have an API built in Laravel (Dingo) and it works perfectly. However I have a problem with implementing phpunit to unit test my API class ProductControllerTest extends TestCase { public function testInsertProductCase() { $data = array( , "description" => "Expensive Pen" , "price" => 100 ); $server = array();...

Handling a big interface


android,xml,interface
I'm currently programming an app, but I'm still new to android studio. ![Interface]: http://imgur.com/sofBtth That's the interface I'm working on, but it seems to be too large to use it properly (there are still fields like address, phone, etc. and 2 buttons under the last one that can't be seen)....

Fighter class does not implement interface member


c#,class,interface
And I am getting this error: Error 1 'Fight.Fighter' does not implement interface member 'Fight.IFighter.Utok(Fight.IFighter)' This is the first time I am trying to learn working with interfaces, so sorry for dump question. Any ideas? I have following code: Interface: interface IFighter { string GraphicLife(); bool IsLive(); int Obrana(int utocneCislo);...

Golang switch between structs


struct,go,interface,switch-statement
I'm new to golang and I'm trying to create a function that, based on the struct it's used on, will return a formatted string using Sprintf type Name struct { Title string First string Last string } type Location struct { Street string City string State string Zip string }...

DialogFragment callback to Target Fragment using interface


android,android-fragments,interface,callback,android-dialogfragment
I am trying to send some data from a dialogfragment to the targeted fragment but its not working. I have written the following code, but it through exception: java.lang.NullPointerException: Attempt to invoke interface method 'void com.x.x.FragmentAlertDialog$Communicator.setI(java.lang.String)' on a null object reference Code: public class FragmentAlertDialog extends DialogFragment { Communicator callback;...

Symfony2 & PHPUnit - Access getContainer()


php,symfony2,login,parameters,phpunit
I have a problem with my PHPUnit test on symfony2. To connect to my application, I use a web service, so I created a UserProvider. In my function loadUserByUsername I use symfony2 parameters saved in app/config/parameters.yml. As I'm not in a controller I need to use the global variable $kernel...

Declare interface in static context(for example in static block) in java?


java,interface,static-block
for example public class Test { static { interface ITest {} } } Here the interface ITest is declare within the static block... The purpose is to know why this happening and not what is happening.. Interfaces are inherently static then why it can not be declared in static block...

Issue with interface and parameter


java,parameters,interface
I have problem with interface and parameters: public class Functions { public static Double getInfoSum(TreeMap<String, Iinterface> map){ ....some counting } } public class ExampleClass { private TreeMap<String, ExampleClassItem > xxxx; public static void SomeFunction(){ Functions.getInfoSum(xxxx); //HERE IS ERROR } } public class ExampleClassItem implements Iinterface { ..... } Is there...

Cannot convert type via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion


c#,interface,type-conversion
In C#, if I have a parameter for a function where the parameter type is of an interface, how do a pass in an object that implements the interface. Here is an example: The parameter for a function is as follows: List<ICustomRequired> The list that I already have is as...

CI accessing property on interface


php,laravel,interface,scrutinizer
I'm using scrutinizer to analyze my code. And almost everything has been fixed but I can't seem to fix this issue. Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check? I see the problem beceause it's an interface that...

Static interface equivalent C#


c#,inheritance,interface,static
I've worked with singletons in the past and I'm aware it's a solution for some people who are trying solve the static interface problem. In my case, I can't really use a singleton because I have an external class that I'm inheriting from and I have no control over this...

Laravel 5.1 PHPUnit with “use DatabaseMigrations;” Produces Error when Accessing Test DB


php,laravel,phpunit,laravel-5.1
I'm just learning PHPUnit with Laravel 5.1. I'm using "use DatabaseMigrations" to migrate the test database for each test, which I set in my phpunit.xml: <php> ... <env name="DB_DATABASE" value="project_test"/> ... </php> I've setup a bunch of basic tests as I go along to check instantiation, factories, etc, but I...

HuggableInterface in PHP and PSR-8


php,interface
On the PHP Framework Interop Group site (the maintainer of PSRs), there is a draft PSR-8 Huggable Interface: namespace Psr\Hug; /** * Defines a huggable object. * * A huggable object expresses mutual affection with another huggable object. */ interface Huggable { /** * Hugs this object. * * All...

database restore for integration tests with phpunit


php,testing,phpunit,integration-testing
I'm using phpunit and I'd like to know if there is a correct form for restoring the database before running integration tests. At the moment I'm calling an sql server script with php exec() on the testcase setUp method, but don't know if this is the best choice class...

Unable to find wrapper when testing Guzzle call with PHPUnit


php,codeigniter,phpunit,guzzle
I am writing a unit test for an API that I am developing. The API is written in the Codeigniter framework, that calls another API using Guzzle. The test I am writing verifies that the API call returns the correct response. The Test.php file contains the following code require '/application/libraries/apiWrappers/Breathehr.php';...

“Attempting to use an incompatible return type” with Interface Inheritance


java,inheritance,interface
I'm running into a problem with incompatible return types using inheritance. public interface A { } public interface B extends A { } public interface C { Map<String, A> getMapping(); } public interface D extends C { Map<String, B> getMapping(); } Is there a way to make this work? Right...

Symfony Functional Testing: how to understand why the test fails (with a 500 Error)


php,symfony2,phpunit,functional-testing
I'm writing functional tests for a controller that registers a new user in the app. The test I'm writing fails because of a 500 HTTP error. I'm using $response = $client->getResponse(); print_r($response->getContent());exit; to print the HTML to see what is happening but the HTML is incomplete in my console (PHPStorm)...

PHPUnit: Testing RestFul API with die response


php,json,api,zend-framework2,phpunit
I am trying to PHPUnit test an action in my ZF2 project. The APIs return a JSON string using die($jsonObject). This causes the PHPUnit test to stop processing and just die a JSON response. public function testStartupAction() { $this->dispatch('/api/v3/startup', "POST", array()); $this->assertJson('{"status":false,"message":"Please enter the UID","data":null}'); } assetJson method is never...

Generic Interface missing implementation


vb.net,interface,implements,generic-interface
I have a generic interface, even if I state the type when I implement it, it says the implemented classes misses all implementation of members. The interface Interface IBuilder(Of T) Function Number(ByVal literal As String) As T End Interface The implement Class BracketsBuilder Implements IBuilder(Of String) Public Function Number(number__1 As...

Symfony2: changing the request class and updating the test environment


php,symfony2,request,phpunit
I have modified the base Request class of my application as explained in the accepted answer of this question. It works very well, except when launching my functional tests, I get the following error: Controller "My\Bundle\AppBundle\Controller\MyController::searchAction()" requires that you provide a value for the "$request" argument (because there is no...

Interface for Child Class that Inherits from parent class without reimplementing parent class


c#,oop,inheritance,interface
Currently I have the following: public class ChildClass : ParentClass {... ParentClass implements an interface as follows (I need ParentClass to be instantiated and therefore can't be abstract): public class ParentClass : IParentClass {... I also want child class to implement an interface so that I can mock this class...

Why does a callback method needs to return something? [on hold]


java,interface,callback,return-value
I have never before seen such a thing, so let's say I have such listener object: MyWhateverListener dafuqListener = new MyWhateverListener() { @Override public void onSuccessCall(String s) { // success call } @Override public void onFailCall(boolean b) { // fail call } @Override public boolean onDafuqCall(int i, boolean b) {...

Android Fragments fundamentals: why? Is this conceptually wrong?


android,interface,fragment,communication
I bring you a question about "proper programming" in Android. I am currently developing an app using fragments. It involves dynamically added fragments to Activity, fragments inflated from XML, nested fragments from XML or dynamically added. Let's just say, a bit of everything. The concept this question focus is the...

How to implement repeated behavior when inheritance isn't an option


java,oop,interface
I have two classes which share some properties and behavior. One such cluster of common behavior is manipulation in 3D space. As such, each implements interface Transformable: public interface Transformable { public void position (double x, double y, double z); public void position (Tuple3d tuple); public void rotateDeg (double yaw,...

Are interfaces a valid substitute for utility classes in Java 8? [duplicate]


java,class,interface,java-8,utility-method
This question already has an answer here: Java 8: Interface with static methods instead of static util class 4 answers For the past decade or so, I've been using the pattern below for my Java utility classes. The class contains only static methods and fields, is declared final so...

Laravel Interfaces


php,laravel,interface,namespaces
I used the following tutorial to get an idea about interfaces: http://vegibit.com/what-is-a-laravel-interface/ But I wanted to change the directory of where I am putting my interfaces to "App/Models/Interfaces". And so I did. But now I cannot get it to work anymore. Here is my code: Routes.php App::bind('CarInterface', 'Subaru'); Route::get('subaru', function()...

Searching for an example of class-binding by a interface


java,interface,mvp
I am trying try to implement a MVP-Pattern example in Java but I do not know how the interface connection between the Presenter and the View works! Does someone know a good example of this? More details: In some sources a class diagram looks like this diagram The arrow between...

WP_UnitTestCase - how to configure the include_path correctly with phpunit PHAR


wordpress,phpunit,composer-php
I'm trying to write a php unit test for my wordpress plugin and have been following the writing-wordpress-plugin-unit-tests tutorial. I've cloned the 'core.trac.wordpress.org/browser/tests/trunk/includes' locally I have installed phpunit via the PHAR mechanism as described here : https://phpunit.de/manual/current/en/installation.html#installation.requirements. I also have a composer.json configuration [14:11:[email protected]~]$ phpunit --version PHPUnit 4.7.3 by Sebastian...

unable to start activity from onPostexecute() using interface


android,interface,android-asynctask
I need to start another activity from the onPosExecute method of the AsyncTask. The AsyncTask is a seperate class and not in any activity class. I have used an interface to do so. The codes are: This is the onPostExecute() method @Override protected void onPostExecute(String json) { Log.v("JSON", json); Log.v("updateUI",""+updateUI);...

phpunit no tests executed


php,phpunit
I have a 'No tests executed' with phpunit.. This line works $ phpunit install/InstallDbTest.php ... <result expected> ... $ cat suites/installtests.xml <phpunit> <testsuites> <testsuite name="database"> <file>install/InstallDbTest.php</file> </testsuite> </testsuites> </phpunit> $ phpunit -c suites/installtests.xml PHPUnit 4.7.4 by Sebastian Bergmann and contributors. Time: 130 ms, Memory: 11.25Mb No tests executed! Does anyone...

Interface constant declaration example in Java's SDK


java,interface,constants
Is there an example of an Interface in Java's built-in library (JDK) that contains a constant field? From the documentation, constant declaration can be defined in interfaces, but I can't remember seeing such. public interface OperateCar { // constant declarations, if any ... } ...

C# How i use linq with explicit interface attribute?


c#,linq,inheritance,interface,explicit
i have one class with two inheritance interfaces and yours attributes are explicits because both have some equals attributes, so, i need use LINQ with this class, but i can't access the explicits attributes when i use "select new Foo" ... look the case: public class QuestaoMontaProva : IQuestao, IExercicio...

Get List of Elements in Tree with specific Field Value


vb.net,linq,properties,interface
I have an Interface like this: Public Interface TreeSelectorAttributes Property selectedInTreeSelector As Boolean Property Name As String ReadOnly Property childs As IEnumerable(Of TreeSelectorAttributes) End Interface and I have a TreeView which has a List of this TreeSelectorAttributes: Public Property rootList As IEnumerable(Of TreeSelectorAttributes) now after the User chooses which elements...

Why is interface variable instantiation possible?


c#,variables,interface,instance
As far as I know, interfaces cannot be instantiated. If this is true, why does the below code compile and execute? It allows you to create a variable interface. Why is this possible? Interface: public interface IDynamicCode<out TCodeOut> { object DynamicClassInstance { get; set; } TCodeOut Execute(string value = "");...

Avoiding type checking when interface method parameters are abstract


c#,oop,interface
My interface looks like this: public interface UserHandler { CheckUsernameResponse CheckUsername(CheckUsernameRequest request); } The request and response types in the signature are abstract classes, giving a usage of something like: var fooHandler = new FooUserHandler(); var fooResponse = fooHandler.CheckUsername( new FooRequest { id = 1, FooProperty = "abc" }); or...

Utility method expects interface and doesn't accept a class that implements said interface [duplicate]


java,interface
This question already has an answer here: Why we can't do List<Parent> mylist = ArrayList<child>(); 2 answers I'm working on a web development project, and I'm working on several apps with "news feed" functionality. I want to make sure that every item with a picture flips a switch back...

Laravel 5.1 Unable to Run Test on User Password Mutator


php,unit-testing,laravel,phpunit,laravel-5.1
I have a password mutator: /** * Mutator for setting the encryption on the user password. * * @param $password */ public function getPasswordAttribute($password) { $this->attributes[ 'password' ] = bcrypt($password); } That I'm trying to test: /** * A basic check of password mutator. * * @return void */ public...

Matlab - Constructor doesn't initliaize member values


matlab,variables,interface,constructor
Dear lovely community, I already looked in Google and in the forum and also found some interesting posts. But in the end I still didn't get it worked. So, I am going to post the question here. I know in Matlab are already get/ Set methods implemented, but I am...

Define type for PHPUnit's mock objects


php,phpunit,phpdoc
I was wondering if its possible to use phpdoc to define some object in specific scope (inside a method only) as PHPUni's Mock, so in that method i can take advantage of type-hints, such as ->expected, ->methods and so on, just like when you just create the mock without addressing...

Methods defined in an interface can no be used from another class


c#,entity-framework,interface
I am using Entity Framework 4.1 and code-first approach. I have the following intefaces namespace BackupCore.Contracts { public interface IEntity { DbSet getDbSet(BackupCoreContainer context); bool isNew() ; } } namespace BackupCore { interface IDao<IEntity> { IEntity Save(IEntity ent); IQueryable<IEntity> GetAll(); bool Delete(IEntity ent, out String errMsg); void SaveChanges(); } }...

Android pass arguments from dialog to calling activity


java,android,interface
I'm having problems getting data from my dialog to the calling activity. Been following the android documents, but haven't had luck. I just want to capture a string that someone enters in an edit text box of my dialog. Here is my setup. public class CrossoverMainActivity extends Activity implements CrossoverSaveDialog.NoticeDialogListener...

How to unit test a data extraction method


php,unit-testing,phpunit
I have created a method which interacts with a framework, pulling out order items which have a completed status. However, how can I unit test my method to ensure it behaves correctly... class A { public function extractData() { // extract data from framework $dataCollection = FrameworkX->getDataCollection('sales/orders'); $dataCollection->filter('state', 'complete'); return...