如何模拟用PhpUnit查看另一个模型的一个或多个实例的模型方法?

时间:2019-06-20 20:03:17

标签: php laravel phpunit laravel-5.8

我正在对道路的不同响应进行单元测试(通常情况下,道路受身份验证保护)。 我设法模拟了用户身份验证。但是,由于存在数据库连接错误,因此无法模拟调用数据库的模型的方法。

您知道如何在不调用数据库的情况下模拟他的方法吗?

这就是我所做的。

  • 控制器
    class XYZController extends Controller{

    ...
        public function index(Request $request){
            $user   = Auth::user();
            $person = $user->person()->first(); // how mock the method person - from the I have the database error.
            $phone  = $user->phone()->first();// how mock the method phone
            $prefix = $phone->country()->first()->code; // how mock the method country
            $email  = $user->email;
            $pays   = Pays::where('xyz', false)->get(); // how mock the method person
    ...
            return view('xyz',[
                ...
            ]);
        }
    ...
    }
  • 测试
    class XYZTest extends TestCase{

        public function testRouteMain(){
          $user = factory(User::class)->make();
          $person = factory(Person::class)->make();

          $this->withoutMiddleware();
          $this->be($user);

          $mockUser = Mockery::mock(User::class);

          $mockUser->shouldReceive('person')->andReturn(collect());
          $mockUser->shouldReceive('first')->andReturn($person);
          $this->app->instance(User::class, $mockUser);
          $reponse = $this->get(route('xyz_route'));

          $this->assertEquals(Response::HTTP_OK, $reponse->>getStatusCode(), 'The status code expected is '.Response::HTTP_OK);// I put the doubles ">>" on purpose , it's to avoid having the blockquote
       }
    }

1 个答案:

答案 0 :(得分:0)

尝试一下:

$mockUser = Mockery::mock(User::class);
$this->app->instance(User::class, $mockUser);
          ^^^^^^^^^^

此外,如果我没记错的话:

$mockUser->shouldReceive('person')->andReturn(collect());
$mockUser->shouldReceive('first')->andReturn($person);

为每个调用的方法重复。