laravel为发送电子邮件写了正确的测试

时间:2018-04-06 08:37:11

标签: php laravel phpunit

我想知道如何为我的电子邮件发送方法编写适当的单元测试。这是一个问题,因为在内部方法中我从Auth对象获取数据。我应该在Request中发送用户ID吗?

 public function sendGroupInvite(Request $request){

        foreach ($request->get('data') as $item){

            $invitations = new \App\Models\Invitations();
            $invitations->user_id = Auth::id();
            $invitations->name = $item["name"];
            $invitations->email = $item["email"];
            $invitations->status = 0;
            $invitations->token = \UUID::getToken(20);
            $invitations->username = Auth::user()->name;
            $invitations->save();

            $settings = UserSettings::where('user_id', Auth::id())->first();

            $email = $item["email"];
            $url = 'https://example.com/invite/accept/'.$invitations->token;
            $urlreject = 'https://example.com/invite/reject/'.$invitations->token;

            $mailproperties =  ['token' => $invitations->token,
                                'name' => $invitations->name,
                                'url' => $url,
                                'email' => $email,
                                'urlreject' => $urlreject,
                                'userid' => Auth::id(),
                                'username' => Auth::user()->name,
                                'user_name' => $settings->name,
                                'user_lastname' => $settings->lastname,
                                'user_link' => $settings->user_link,
            ];

            $this->dispatch(new SendMail(new Invitations($mailproperties)));
        }

        return json_encode(array('msg' => 'ok'));
    }

我使用Auth获取用户名和用户ID。当我对其进行测试时,它不起作用,因为Auth它是null

2 个答案:

答案 0 :(得分:1)

我会嘲笑队列,类似于此。 Mock Documentation

class MailTester extends TestCase{

/**
* @test
*/
public function test_mail(){
    Queue::fake();

    // call your api or method

    Queue::assertPushed(SendMail, function(SendMail $job) {
        return $job->something = $yourProperties;
    });
}

答案 1 :(得分:0)

你可以尝试"充当"处理Auth :: user()。

...
class MyControllerTest extends TestCase{

    /**
    * @test
    */
    public function foo(){
        $user = App\Users::find(env('TEST_USER_ID')); //from phpunit.xml
        $route = route('foo-route');
        $post  = ['foo' => 'bar'];

        $this->actingAs($user)//a second param is opitonal here for api
             ->post($route, $post)
             ->assertStatus(200);
    }
}