Lessons Learnt: PHPUnit for Beginners

Martin Betz
3 min readJul 9, 2020

--

I took the course PHPUnit for Beginners by Laravel Daily. 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

How to create content with custom values with Eloquent

How to setup test database?

  • phpunit.xml overwrites .env.testing
  • Edit DB_CONNECTION for MySQL/sqlite
  • Change value of DB_DATABASE into value=":memory:" to get fast in memory store

What does RefreshDatabase trait do?

  • It Runs migrations
  • Creates a fresh database
  • Usage
  • use Illuminate\Foundation\Testing\RefreshDatabase; above class
  • use RefreshDatabase; in class, not single test

When should you use a MySQL test database?

  • When you use raw MySQL statements for the following features:
  • Date formatting
  • String functions
  • Date differences
  • Geospatial features

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

  • <server name="DB_CONNECTION" value="MySQL"/>
  • <server name="DB_DATABASE" value="name_of_db"/>

Why to test data and not visuals (assertSee)?

  • To avoid false positives because of incomplete results
  • Example
  • Blade: show product name {{ $product->name }}
  • Data: ['name' => 'Product 1000]
  • Visual test: $response->assertSee('Product 1') would turn green and create a false positive

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

What do unit tests capture?

  • Internal logic
  • No Endpoint
  • Data processing

How to create a Laravel service to translate currency

  • Create service in app\services -> CurrencyService.php
  • Import using use App\Services\CurrencyService
  • Call new CurrencyService()->convert();
  • No changes in database needed

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

  • This is also called accessor
  • On model Product.php

How to create an unit test?

  • art make:test NAME --unit

How to paginate in controller and view?

  • (In Controller): $products = Product::paginate(10);
  • In View: {{ $products->links() }}

How to call factories?

  • factory(Product::class, 10)->create();

How to echo variable result into log?

  • Call info($var) in your code

How to test if login works?

  • Create user
  • Post login data and set response

How to quickly log in for tests?

  • $this->actingAs($user)->get('/')

How to protect a route via auth?

  • Route::get('/')->middleware('auth')

Easiest way to add admin?

  • Add field to user model: is_admin
  • Add to fillable in model
  • Create middleware app\Http\Middleware\IsAdmin (see following snippet)
  • Add middleware to App\Kernel
  • Add middleware to your route Route::middleware('auth', 'is_admin')

Which visual assertions are usual?

  • $response->assertSee()
  • $response->assertDontSee()

How to create simple factory states?

  • Example: is_admin, yes/no
  • Create private function with factory and optional parameter in it

How to store everything you get via form?

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

  • $this->post('products', ['name' => 'Test 1', 'price' => 99.99]);

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

  • $this->assertDatabaseHas('products', ['name' => 'Test 1', 'price' => 99.99]);

How to test whether saved data gets returned?

  • $product = Product::orderBy('id', 'desc')->first();
  • $this->assertEquals('String', $product->name);
  • $this->assertEquals('price', $product->price);

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

  • $product = Product::first();
  • $response->assertSee('value="' . $product->price . '"');

How to update all data from a request?

Where and how to create a form request?

  • app/Http/Requests/UpdateProductRequest.php

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?

How to create a delete item view?

Unlisted

--

--