-
UpdateBookJob, UpdateBookJobTest One way or another, we have to use models in our job, are there any ideas how this can be avoided? I want to make the code testable without a database.
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I got what I wanted. How do you like this approach? |
Beta Was this translation helpful? Give feedback.
-
@Batisska interesting approach 👍 I would like to add a couple of approaches that are also possible just in case someone lands here later and would like more options, especially that the repository approach requires a change in code structure. Recommendation <server name="DB_CONNECTION" value="sqlite"/>
<server name="DB_DATABASE" value=":memory:"/> With this method we ensure that the entire database suite is working (migrations, models and jobs). As for testing features and operations that call the jobs that access the database, there are three ways you could go about this: 1. Mock the Job (recommended) In your test: $mUpdateBookJob = Mocker::mock(UpdateBookJob::class);
$mUpdateBookJob->shouldReceive('handle')->andReturn($result);
$this->instance(UpdateBookJob::class, $mUpdateBookJob); Where This approach is the most recommended since it's built-in to Lucid & Laravel, and it doesn't enforce a pattern or code structure which in the case of existing projects may require a lot of refactoring time. 2. Repository Pattern The one suggested by @Batisska is a perfect example. Where you'd create an access layer that you can mock when injecting into the job. 3. Mock Book Model (not recommended) In the test: $mBook = Mockery::mock(Book::class);
$this->instance(Book::class, $mBook); From there on, any call to a method from within the Book class must be mocked. Unless you'd opt for a partial mock so you'd only need to mock the methods that go to the database (i.e. Partial mock: $mBook = Mocker::mock(Book::class)->partial(); This method is not recommended because there are too many internal methods within Eloquent that you may need to mock although you don't use them in the tests, leading to unnecessary boilerplate. However, this method is recommended in cases where the injected class is not an Eloquent model. |
Beta Was this translation helpful? Give feedback.
testing repositories
I got what I wanted. How do you like this approach?