Unit Test Laravel's FormRequest

前端 未结 2 1805
北恋
北恋 2020-12-02 23:34

I am trying to unit test various custom FormRequest inputs. I found solutions that:

  1. Suggest using the $this->call(…) method an

相关标签:
2条回答
  • 2020-12-03 00:18

    I found a good solution on Laracast and added some customization to the mix.

    The Code

    public function setUp()
    {
        parent::setUp();
        $this->rules     = (new UserStoreRequest())->rules();
        $this->validator = $this->app['validator'];
    }
    
    /** @test */
    public function valid_first_name()
    {
        $this->assertTrue($this->validateField('first_name', 'jon'));
        $this->assertTrue($this->validateField('first_name', 'jo'));
        $this->assertFalse($this->validateField('first_name', 'j'));
        $this->assertFalse($this->validateField('first_name', ''));
        $this->assertFalse($this->validateField('first_name', '1'));
        $this->assertFalse($this->validateField('first_name', 'jon1'));
    }
    
    protected function getFieldValidator($field, $value)
    {
        return $this->validator->make(
            [$field => $value], 
            [$field => $this->rules[$field]]
        );
    }
    
    protected function validateField($field, $value)
    {
        return $this->getFieldValidator($field, $value)->passes();
    }
    

    Update

    There is an e2e approach to the same problem. You can POST the data to be checked to the route in question and then see if the response contains session errors.

    $response = $this->json('POST', 
        '/route_in_question', 
        ['first_name' => 'S']
    );
    $response->assertSessionHasErrors(['first_name');
    
    0 讨论(0)
  • 2020-12-03 00:20

    Friends, please, make the unit-test properly, after all, it is not only rules you are testing here, the validationData and withValidator functions may be there too.

    This is how it should be done:

    <?php
    
    namespace Tests\Unit;
    
    use App\Http\Requests\AddressesRequest;
    use App\Models\Country;
    use Faker\Factory as FakerFactory;
    use Illuminate\Routing\Redirector;
    use Illuminate\Validation\ValidationException;
    use Tests\TestCase;
    use function app;
    use function str_random;
    
    class AddressesRequestTest extends TestCase
    {
    
    
        public function test_AddressesRequest_empty()
        {
            try {
                //app(AddressesRequest::class);
                $request = new AddressesRequest([]);
                $request
                    ->setContainer(app())
                    ->setRedirector(app(Redirector::class))
                    ->validateResolved();
            } catch (ValidationException $ex) {
    
            }
            //\Log::debug(print_r($ex->errors(), true));
    
            $this->assertTrue(isset($ex));
            $this->assertTrue(array_key_exists('the_address', $ex->errors()));
            $this->assertTrue(array_key_exists('the_address.billing', $ex->errors()));
        }
    
    
        public function test_AddressesRequest_success_billing_only()
        {
            $faker = FakerFactory::create();
            $param = [
                'the_address' => [
                    'billing' => [
                        'zip'        => $faker->postcode,
                        'phone'      => $faker->phoneNumber,
                        'country_id' => $faker->numberBetween(1, Country::count()),
                        'state'      => $faker->state,
                        'state_code' => str_random(2),
                        'city'       => $faker->city,
                        'address'    => $faker->buildingNumber . ' ' . $faker->streetName,
                        'suite'      => $faker->secondaryAddress,
                    ]
                ]
            ];
            try {
                //app(AddressesRequest::class);
                $request = new AddressesRequest($param);
                $request
                    ->setContainer(app())
                    ->setRedirector(app(Redirector::class))
                    ->validateResolved();
            } catch (ValidationException $ex) {
    
            }
    
            $this->assertFalse(isset($ex));
        }
    
    
    }
    
    0 讨论(0)
提交回复
热议问题