doucuo4413 2017-01-05 07:41
浏览 14

我如何模拟这个进行测试?

The following is a simplified class of the controller I am working on:

class UserController extends Controller {
    protected $user;

    public function __construct(User $user) {
        $this->user = user;
    }

    public function contact(ContactFormRequest $request) {
        $user = $this->user
            ->where('email',  $request->email)
            ->with(['orders' => function($q) {
                $q->orderBy('created_at', 'desc')
                    ->first();
            }])
            ->first();

        return view('contact', ['user' => $user]);
    }
}

This is the test case I have thus far:

class ExampleTest extends TestCase {
    public function setUp () {
        $this->mockUser = Mockery::mock(Model::class, User::class);
        $this->app->instance('User', $this->mockUser);
    }

    public function testContactForm() {
       $this->userMock
           ->shouldReceive('where')
           ->once()
           ->with('email', 'fake@email.com')
           ->andReturn(new Collection(new User, new User));

        $this->visit('contact-form'); 
    }
}    

I'll admit I am writing this from memory instead of having the existing code in front of me. But this test at work passes PHPUnit. The problem is that the visit throws an error and I have additional ->see('something') test I need to make.

I need the rest of the mock that gives a full and usable user mock to the controller and view.

I expect it looks something like (this is where the code goes awry)

$this->userMock
    ->shouldReceive('where')
    ->once()
    ->with('email', 'fake@email.com')
    ->andReturn(new Collection(new User))
    ->shouldReceive('with')
    ->once();
    ->with(['orders' => function($q) {
        $q->orderBy('created_at', 'desc')
            ->first();
        }])
    ->andReturn( **something** )
    ->shouldReceive('first')
    ->once()
    ->andReturn(new Collection(new User));
  • 写回答

1条回答 默认 最新

  • dongtie0929 2017-01-06 10:09
    关注

    Do not mock the ORM (knows as Don't mock third-party libraries or only mock types you own). Instead, provide a test database (either with fixture or afactory), so the code actually finds the user you want

    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)