Why we test… the two other tests I’m forgetting to write

This morning was spent fixing something, which frankly, I should have known better! However, when you’re coding and project managing on your own, it’s not easy to keep everything rolling.

When I write new Repository methods, I leave a comment note @totest to remind me to come back and write some tests!

However, I’ve missed writing 2 simple types of tests which would have taken 20 mins and then saved me an hour this morning. So I thought I’d share with you lot.

In My Laravel Middleware I have a method which checks the UserId provided is one of our students.

    $user = $this->userRepo->findByUidOrFail($this->fetchUser());

However, because I haven’t filled in any tests on that Repo yet, I’ve been going around the houses trying to fix a problem which some simple unit tests would have flagged 2 days ago. The return wasn’t erroring if the user isn’t there AND was returning a Collection when it should have been giving me a Model

So along with unit testing positive results from a successful method call, we should be writing two other types of tests.

The Exception Test.

Clearly this method name says, find…OR FAIL!!!! However, it wasn’t throwing a ModelNotFoundException on failing, it was just returning a Collection!

The tests I have written to assert it’s working now,

// UserRepositoryInterfaceTest.php /** * @expectedException ErrorException */ public function test_findByUidOrFail_incorrect_params() { $records = $this->theRepo->findByUidOrFail(); } /** * @expectedException IlluminateDatabaseEloquentModelNotFoundException */ public function test_findByUidOrFail_modelNotFound() { $this->theRepo->findByUidOrFail("foo"); }

The returned type Test.

It seems weird to test you’re getting the write variable type back, however, it’s crucially important. Because what if you expect an integer, 2, and you’re returned a string of “2”. Any triple if’s === would fail and probably throw something else off.

So we test for cast types. In this example, I assert the Model by looking for a certain method’s availability or not.

// UserRepositoryInterfaceTest.php

public function test_findByUidOrFail_is_model()
    $record = $this->helper->createAUser();
    $result = $this->theRepo->findByUidOrFail($record->uid);


// TestHelper.php

public function assertIsModel($obj)
        method_exists($obj, 'getTable'),
        'obj is not a Model'

By Dan Course

Senior Instructional Designer. Partnerships, people, products, delivery, agile tech and online edu. Naturally curious, innovative and willing to challenge the status quo.

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: