LogoNavigate back to the homepage

To Test Laravel Request layer (validation rules) from the fake controller

Yish
September 24th, 2020 · 1 min read

From my situation, I need to test my request validation rules, but here is a problem, I think I DO NOT make a request to the real route, so I have to create a fake controller and add to my test case, here is my solution.

1/**
2 * @dataProvider resend
3 */
4public function testOrderResendRequest($payload, $assertions)
5{
6 $route = Route::addRoute('POST', 'fake/resend', '\Tests\Feature\FakeController@resend')
7 ->prefix('api')->name('fake.resend');
8 $this->json('POST', $route->uri, $payload)
9 ->assertJsonValidationErrors($assertions);
10}

I added a route to request, and also making a fake controller in the test case, finally, I did a json request to the fake route. By the way, I used @dataProvider to validate any situations I wanted to test properties, it’s really useful.

Next, I made FakeController in the same class.

1class FakeController extends Controller
2{
3 public function resend(OrderResendRequest $request) // Here is my request layer.
4 {
5 return response()->json(['data' => 'hello']); // whatever you wanted putting in.
6 }
7}
8
9public function testOrderResendRequest($payload, $assertions)

What do I need to do this? I used validator()->make(), I can’t validate Rule, for example, Rule:requireIf and others closures, if your rules are only having string rules, you can do for:

1$rules = (new OrderResendRequest)->rules();
2$validator = validator()->make($payload, $rules);
3
4$this->assertFalse($validator->fails());
5// and what you want to test

More articles from Yish

Ordering Laravel middleware priority

Ordering the middleware through, I traced the underlying instance Kernel

August 17th, 2020 · 1 min read

You should know the tricks of Carbon

For my situations, I need to set period time finishing our project logics, but here is a problem, how can I mock the now from my setting? Fortunately, the php package Carbon provides a few methods to do this.

July 30th, 2020 · 1 min read
© 2019–2020 Yish
Link to $https://twitter.com/yishlaiLink to $https://github.com/Mombuyish