如何测试从.json文件读取信息的Laravel控制器

时间:2019-04-03 16:16:30

标签: php laravel-5 phpunit

我是Laravel和PHPUnit的新手。我正在尝试测试控制器,该控制器读取.json文件,执行一些计算并返回结果,例如[3,3,2,0.5]。

如何将.json文件或某些值发送到控制器并检查反馈结果?

提前谢谢

控制器:

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文件:

{
    "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
}

0 个答案:

没有答案