模拟获取参数symfony2和phpunit

时间:2017-03-14 11:47:46

标签: symfony unit-testing phpunit

我想测试它有一个控制器:

$ deviceGet = strtolower($ request-> query-> get(' device'));

我的问题是:如何在我的控制器中模拟它进行测试?

class SetDeviceListenerTest extends \PHPUnit_Framework_TestCase {


     /**
     * @test
     * @dataProvider deviceGetCases
     */
public function shouldSetRequestDeviceWithDeviceGetOnMasterRequest(
    ?string $device
): void {
    $request = $this->getRequestMock();

    $request->expects($this->once())
        ->method('get')
        ->with('device')
        ->willReturn($device);


    /* @var Request $request */
    $request->server = new ServerBag();
    $request->headers = new HeaderBag();

    $event = $this->getEventMock();
    $event->expects($this->once())
        ->method('isMasterRequest')
        ->willReturn(true);

它返回错误,因为

 $request->expects($this->once())
        ->method('get')
        ->with('device')
        ->willReturn($device);

失败

谢谢!!

1 个答案:

答案 0 :(得分:3)

我自己找到了答案(我只需要一位朋友):

$request->query= new ParameterBag(['device'=>$device]);