I
I
igor11122019-03-17 04:16:37
PHPUnit
igor1112, 2019-03-17 04:16:37

How to make a mock of your own service class in a test?

I have a controller -

class PostController extends Controller
{
    private $postindexer;

    public function __construct(PostIndexer $postindexer)
    {
        $this->postindexer = $postindexer;
    }

    public function store(Request $request)
    {
        $post = new Post;
        $post->name = $request->name;
        $post->save();

        $this->postindexer->index($post);

        return response()->json($post, 201);
    }
}

In the structure of this controller, my service class "PostIndexer" is introduced, which, after creating the post, puts this new, just created post into the elastisearch index.
To test the controller, I use a functional test - I just go to the address, check the database, look at the response code. At the same time, I do not need this new post to be entered into the elasticsearch index.
The test method looks like this -
public function testStore()
{
    $params = [ 'title' => 'New Post', 'body' => "I'm a content"];

    $this->post('/admin/posts', $params)->assertStatus(201);

    $post = Post::first()->toArray();

    $this->assertDatabaseHas('posts', $post);
}

The question is - how can I make this line of code in the "PostController" class not work on a test post request -
$this->postindexer->index($post);
How do I mock this thing so that it does not get called?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex Wells, 2019-03-17
@igor1112

https://laravel.com/docs/5.8/mocking#mocking-objects

$this->mock(PostIndexer::class, function ($mock) {
    $mock->shouldReceive('index')->once();
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question