如何在不发送电子邮件的情况下测试此代码段?
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()));
}
但是这样我必须在测试文件夹中设置邮件配置文件,并且sustem发送一封电子邮件:(
答案 0 :(得分:5)
我需要在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。
答案 1 :(得分:1)
创建一个app/config/testing/mail.php
文件并在其上设置假装为true:
<?php
return [
'pretend' => true,
];