【问题标题】:Laravel unit test how to test Event with email without send an emailLaravel 单元测试如何在不发送电子邮件的情况下使用电子邮件测试事件
【发布时间】:2014-11-04 05:57:27
【问题描述】:

如何在不发送电子邮件的情况下测试这个 sn-p?

public function forgot() 
    {
        $isValid = $this->updateForm->valid(Input::only('email'));
        if ($isValid) {
            $result = $this->user->forgot($this->updateForm->data());
            if (isset($result['user']) && ($result['success'] > 0)) {
                Event::fire('user.mail.forgot', array('data'=>$result['user']));
                return Response::json(array('success'=>1),200);
            } 
            $error = isset($result['error'])?array_pop($result):trans('user.generror');
            return Response::json(array(
              'success'=>0,
              'errors' => array('error'=>array($error))),  
            200);
        }
        return Response::json(array(
                    'success' => 0,
                    'errors' => $this->updateForm->errors()), 
                    200
        );
    }

现在我测试它:

public function _getSuccess($content)
{
    $json = str_replace(")]}',\n", '', $content);
    $native = json_decode($json);
    return $native->success;
}
public function _set200($method, $uri, $parameters = array())
{
    $this->client->setServerParameter('HTTP_X-Requested-With', 'XMLHttpRequest');
    $response = $this->call($method, $uri, $parameters);
    $this->assertResponseStatus(200);
    return $response;
}
public function testUserForgot200Success()
{
    $response = $this->_set200('POST', '/api/v1/users/forgot', array('email' => $this->userEmail));
    $this->assertSame(1, $this->_getSuccess($response->getContent()));
}

但是这样我必须在测试文件夹中设置邮件配置文件,然后系统会发送一封电子邮件:(

【问题讨论】:

    标签: laravel laravel-4 phpunit


    【解决方案1】:

    我需要在 Laravel 5 中这样做,所以如果有人需要,这里有一个解决方案:

    config/mail.php 中替换这个:

    'pretend' => false,

    通过这个:

    'pretend' => env('MAIL_PRETEND', false),

    然后你可以在phpunit.xml中覆盖这个环境变量:

    <php>
        <env name="APP_ENV" value="testing"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
        <!-- Add this line: -->
        <env name="MAIL_PRETEND" value="true" />
    </php>
    

    如果需要,您也可以在.env 文件中覆盖它,但不会影响 phpunit。

    【讨论】:

      【解决方案2】:

      创建一个app/config/testing/mail.php 文件并将其设置为true:

      <?php
      
      return [
      
          'pretend' => true,
      
      ];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-09-22
        • 2011-06-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多