【问题标题】:How to mock a Validation Rule in Laravel如何在 Laravel 中模拟验证规则
【发布时间】:2019-12-14 15:11:48
【问题描述】:

我想模拟一个自定义验证规则(例如 App\Rules\SomeRule)。但是当我运行我的测试时,它给出了一个Mockery\Exception\InvalidCountException: Method...should be called exactly 1 times but called 0 times.

我已经阅读了 Laravel 的文档 on Mockingon custom Validation RulesService ContainersService Providers,但我无法弄清楚为什么我没有成功地模拟规则。

我阅读了this thread,但我很难将它与我的问题联系起来,即“我如何测试我的应用程序是否正在使用此规则”。还是那是我无法测试的东西?

这是我的规则

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class SomeRule implements Rule
{

    public function passes($attribute, $value)
    {
        // some logic, returns TRUE if valid.
    }

    public function message()
    {
        //
    }
}

我的控制器

namespace App\Http\Controllers;

use App\Rules\SomeRule;
use Illuminate\Http\Request;

class LoanController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([
            'email' => ['required', new SomeRule]
        ]);

        // ...insert in database, return json.
    }
}

我的测试

namespace Tests\Feature;

use Mockery;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Rules\SomeRule;

class LoansTest extends TestCase
{
    use RefreshDatabase;

    public function tearDown(): void
    {
        parent::tearDown();
        Mockery::close();
    }

    /** @test */
    public function the_sad_path__when_email_is_invalid()
    {

        $rule = Mockery::mock(SomeRule::class)->shouldReceive('passes')->once();
        $this->app->instance(SomeRule::class, $rule);

        $response = $this->json('POST', '/api/loans', ['email' => 'whatevs@gmail.com']);
    }
}

我尝试了在 AppServiceProvider 中注册 SomeRule 的想法。但这仍然没有做任何事情:

    public function register()
    {
        $this->app->bind(SomeRule::class, function ($app) {
            return new SomeRule();
        });
    }

Github中的代码

【问题讨论】:

标签: php laravel mocking mockery


【解决方案1】:

你需要这样使用

class LoanController extends Controller
{
    public function store(Request $request)
    {
      $request->validate([
        'email' => ['required', new SomeRule()]
      ]);

    // ...insert in database, return json.
   }
}

【讨论】:

  • 你知道两者的区别吗?在documentation 中,它没有()'name' => ['required', 'string', new Uppercase],
  • 你能解决这个问题吗?我试图在测试中模拟自定义验证器的传递方法并抛出“方法....不存在”错误
猜你喜欢
  • 2016-04-08
  • 1970-01-01
  • 1970-01-01
  • 2017-12-01
  • 2021-11-25
  • 2014-01-08
  • 1970-01-01
  • 2016-11-26
  • 2020-05-08
相关资源
最近更新 更多