Lessons Learnt: PHPUnit for Beginners

Martin Betz • June 8, 2020

I took the paid course PHPUnit for Beginners by Laravel Daily and I can highly to purchase it. It is suitable for total testing beginners and walks you through a simple CRUD application.

Here are my takeaways in the format of question and answer. They are sorted by occurence in the course but you can use whatever you need for your application and testing – not everything is related to testing:

Why choose @forelse … @empty … @endforelse for loops?

It covers the case where there is no data

@forelse ($users as $user)
     <li>{{ $user->name }}</li>
@empty
    <p>No users</p>
@endforelse

How to create content with custom values with Eloquent

$product = Product:create([
  'name' => 'Product 1',
  'price' => 99.99
]);

// in your test
$response->assertSee($product->name);

How to setup test database?

What does RefreshDatabase trait do?

When should you use a MySQL test database?

How to set up a MySQL test database in phpunit.xml?

Why to test data and not visuals (assertSee)?

How to get view data of e.g. $products to test?

$view = $response->viewData('products') // was passed to view in controller
$this->assertEquals($product->name, $view->first()->name);

What do unit tests capture?

How to create a Laravel service to translate currency

How to create temporary database/accessor field (e.g. dynamic price in another currency)?

public function getPriceEurAttribute() {
    return $this->price*0.8;
}

How to create an unit test?

How to paginate in controller and view?

How to call factories?

How to echo variable result into log?

How to test if login works?

$response = $this->post('login', [
  'email' => 'EMAIL',
  'password' => 'PW'
]);
// assert where you expect to be redirected to, e.g. home
$response->assertRedirect('/home');

How to quickly log in for tests?

How to protect a route via auth?

Easiest way to add admin?

public function handle($request, Closure $next) 
{
  if (! auth()->user()->is_admin) 
  {
    abort(403);
  }
  return $next($request);
}

Which visual assertions are usual?

How to create simple factory states?

private function create_user(is_admin = 0)
{
  $this->user = factory(User::class)->create([
    'is_admin' => $is_admin,
  ]);
}

How to store everything you get via form?

// Controller

public function store(Request $request)
{
    Product::create($request->all());
    return redirect()->route('home');
}

How to test a POST request with parameter name = 'Test 1'?

How to assert that something is in the database? (db side)

How to test whether saved data gets returned?

How to check whether data for edit is available in view?

How to update all data from a request?

public function update(Product $product, UpdateProductRequest $request)
{
  $product->update($request->all());
  return redirect()->route('products.index');
}

Where and how to create a form request?

public rules() {
  return [
    'name' => 'required',
    'price' => 'required',
  ];
}

How to test an update request?

$response = $this->put('/products/' . $product->id, ['name' => 'Test']);

How to test for session error on 'name'?

$response->assertSessionHasErrors(['name']);

How to update as json API call?

$response = $this->actingAs($this->user)
  ->put('/products/' . $product->id,
  [
    'name' => 'Test',
    'price' => 99.99,
  ],
  [
   'Accept' => 'Application/json', 
  ]);

How to create a delete item view?

<form action={{ route('products.destroy' . $product->id) }} method="POST" onsubmit="confirm('Sure?')">
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="{{ csrf_token() }}">

How to delete item in controller?

public function destroy(Product $product) {
  $product->delete();
  return redirect()->route('products.index');
}

How to assert that data gets deleted?

  1. Create product with factory
  2. $this->assertEquals(1, Product::all())
  3. $response = $this->actingAs($this->user)->delete('products/' . $product->id); (Route missing?)
  4. $response->assertStatus(302)
  5. $this->assertEquals(0, Product::count());