简体   繁体   中英

Mock with all valid methods in PHPUnit

I have following problem:
I want to test controller if no exception is rised during dispatch, but controller uses external library which has own phpunit tests. This library also use external library with own tests and so on...

So my application looks similar to this diagram:

request -> router -> dispatch -> controller -> view

If any error occures during this procces. Application throws exception. I want to test controller, but for now I have to write +50 lines of code to mock all object needed.

Image for example that I pass form from controller to view .
In view I have something like this:

<?php echo $form->openTag('form'); ?>
    <?php echo $form->openTag('fieldset'); ?>
        <?php echo $form->label('firstName'); ?>
        <?php echo $form->input('firstName'); ?>
        <?php echo $form->errorMessages('firstName'); ?>
   <?php echo $form->closeTag('fieldset'); ?>
   <?php echo $form->openTag('fieldset'); ?>
        <?php echo $form->label('gender'); ?>
        <?php echo $form->radio('gender'); ?>
        <?php echo $form->errorMessages('gender'); ?>
   <?php echo $form->closeTag('gender'); ?>
   ...
<?php echo $form->closeTag('form'); ?>

Let's say I have form with 20 inputs... Do you get my point? I have to mock all available methods for this form to pass my test.

It is possible to mock object with all valid methods?

I mean if there is a way to mock class which will have all methods valid? Without need to define anything.
If application will need object of class A it will return object of class A .
If application will need array it will return array
etc..

We know very little of your application context, but by default $this->createMock(Some::class) would create a mock of the entire class - no need to mock every method. Then you can define behavior only to certain methods and that's the entire point of mocking. So in your case it would be your form class I guess, and you will have to set it to the view.

But I would ask what are you testing? If you are testing if the form would throw an exception, you wouldn't want to mock it, but execute it and check for exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM