mercredi 3 avril 2019

how to test Laravel controller which reads information from .json file

I'm new in Laravel and PHPUnit. I'm trying to test controller, which read .json file, execute some calculation and returning result like this [3,3,2,0.5].

How can i send .json file or some value to controller and check feedback results?

Thank you in advance

controller:

namespace App\Http\Controllers;

class payController extends Controller
{
    public function index()
    {
        $ratio = [];
        $ratio1= [];
        $string = file_get_contents("input.json");
        if(!isset($string)){
            echo 'File is empty.';
        } else {
            $json_a = json_decode($string, true);

            $required_income = $json_a['required_income'];

            foreach ($json_a['sms_list'] as $json) {
                $ratio_value = $json['income'] * 100 / $json['price'];
                array_push($ratio, [$ratio_value, $json['price'], $json['income']]);
            }

            foreach ($json_a['sms_list'] as $json) {
                array_push($ratio1, [$json['price'], $json['income']]);
            }

            $count = count($ratio);
            rsort($ratio, 0);

            $smsPrice = [];
            for ($i = 0; $i < $count; $i++) {
                $price = $ratio[$i][1];
                $income = $ratio[$i][2];
                $divisionRequiredIncome = floor($required_income / $price);
                if ($divisionRequiredIncome > 0) {
                    for ($j = 0; $j < $divisionRequiredIncome; $j++) {
                        array_push($smsPrice, $price);
                    }
                    $required_income -= ($income * $divisionRequiredIncome);
                }
            }
            sort($ratio1, 1);
            for ($i = 0; $i < $count; $i++) {
                if ($required_income - $ratio1[$i][1] <= 0) {
                    array_push($smsPrice, $ratio1[$i][0]);
                    break;
                }
            }
        }
        echo '<pre>';
        var_dump($smsPrice);
    }
}

payControllerTest:

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

use App\Http\Controllers\payController;

class payControllerTest extends TestCase
{
    /**
     * A basic unit test example.
     *
     * @return void
     */
    public function test_first()
    {
        $res = payController::index();
    }

}

input.json file:

{
    "sms_list": [
      {"price": 0.5, "income": 0.41},
      {"price": 1, "income": 0.96},
      {"price": 2, "income": 1.91},
      {"price": 3, "income": 2.9}
    ],
    "required_income": 8
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire