M
M
Maxim Medvedev2017-05-23 19:38:40
PHP
Maxim Medvedev, 2017-05-23 19:38:40

How to properly write a test for phpunit and json_encode()?

Hello,
Need help. I started to master automatic tests and reading the documentation and writing a test, I can not solve the problem. I have a code that is responsible for checking user rights and if there are not enough rights, it displays an error page, while the address bar remains the typed address (that is, there is no redirect to 404):

static function check() {
if(self::isAjax()) {
      echo json_encode(array("respons"=>"Ошибка", "status"=>"error"));
      exit;
    }
.......
}

If the request came through ajax, the code above is processed, if the page is opened in a browser, then the corresponding template is displayed.
The test itself:
<?php
declare(strict_types=1);

use PHPUnit\Framework\TestCase;

final class permissionTest extends TestCase
{

    public function test_permission()
    {
      check();
   }
}

The problem is that when I call the test in the console, I get an output like this:
phpunit --bootstrap config.php .
PHPUnit 6.1.4 by Sebastian Bergmann and contributors.

...........{"respons":"Ошибка","status":"error"}

How do I properly process the answer and compose a test?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Koryukov, 2017-05-24
@reimax

It's simple - no need to print the answer in the rights check function.
Moreover, the rights check function should not know anything about whether it starts under Ajax or not. It should just check and return the result (bool, error text, error code, whatever), and already somewhere in the controller (this is the place where you receive the http request data, decide what to do and form the http response) you must turn result in response.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question