Bird
Raised Fist0
Laravelframework~20 mins

Unit tests in Laravel - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Laravel Unit Test Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Laravel unit test?
Consider this Laravel unit test method. What will be the test result when running it?
Laravel
<?php
public function testUserCreation()
{
    $user = User::factory()->make(['email' => 'test@example.com']);
    $this->assertEquals('test@example.com', $user->email);
}
AThe test fails because the user is not saved to the database.
BThe test passes because the email matches the expected value.
CThe test throws an error because User::factory() is undefined.
DThe test fails because assertEquals is used incorrectly.
Attempts:
2 left
💡 Hint
Remember that make() creates an instance without saving it.
📝 Syntax
intermediate
1:30remaining
Which option correctly defines a Laravel unit test method?
Identify the correct syntax for a Laravel unit test method inside a test class.
Apublic function test_example() { $this->assertTrue(true); }
Bpublic testExample() { $this->assertTrue(true); }
Cfunction testExample() { $this->assertTrue(true); }
Dpublic function testExample { $this->assertTrue(true); }
Attempts:
2 left
💡 Hint
Test methods must be public functions with parentheses.
🔧 Debug
advanced
2:30remaining
Why does this Laravel unit test fail with a database error?
This test tries to create a user and check the database, but it fails with a database error. Why?
Laravel
<?php
public function testUserIsSaved()
{
    $user = User::factory()->make();
    $this->assertDatabaseHas('users', ['email' => $user->email]);
}
ABecause the test method is missing a call to refresh the database connection.
BBecause assertDatabaseHas requires a saved model instance, make() is invalid here.
CBecause the users table does not exist in the test database.
DBecause make() does not save the user to the database, so the record is missing.
Attempts:
2 left
💡 Hint
Check the difference between make() and create() in Laravel factories.
❓ state_output
advanced
1:30remaining
What is the value of $count after this Laravel test runs?
Given this test code, what will be the value of $count after execution?
Laravel
<?php
public function testUserCount()
{
    User::factory()->count(3)->create();
    $count = User::count();
}
A1
B0
C3
DThrows an error because User::count() is not accessible.
Attempts:
2 left
💡 Hint
Factories with create() save records to the database.
🧠 Conceptual
expert
2:00remaining
Which option best describes the purpose of Laravel's RefreshDatabase trait in unit tests?
What does the RefreshDatabase trait do when used in Laravel unit tests?
AIt resets the database by running migrations before each test to ensure a clean state.
BIt caches database queries to speed up tests.
CIt disables database transactions during tests.
DIt automatically seeds the database with test data before each test.
Attempts:
2 left
💡 Hint
Think about how to keep tests isolated and avoid leftover data.

Practice

(1/5)
1. What is the main purpose of unit tests in Laravel?
easy
A. To deploy the application to production
B. To create database migrations
C. To check small parts of code to catch errors early
D. To style the user interface

Solution

  1. Step 1: Understand unit test purpose

    Unit tests focus on testing small, isolated parts of code to find bugs early.
  2. Step 2: Compare options with unit test goals

    Only To check small parts of code to catch errors early describes this purpose; others relate to deployment, database, or UI.
  3. Final Answer:

    To check small parts of code to catch errors early -> Option C
  4. Quick Check:

    Unit tests = catch errors early [OK]
Hint: Unit tests check small code parts for bugs early [OK]
Common Mistakes:
  • Confusing unit tests with deployment tasks
  • Thinking unit tests handle UI styling
  • Mixing unit tests with database migrations
2. Which of the following is the correct way to define a test method in a Laravel unit test class?
easy
A. function exampleTest() {}
B. public function testExample() {}
C. public test function example() {}
D. def test_example():

Solution

  1. Step 1: Recall Laravel test method syntax

    Laravel test methods are public functions starting with 'test' or annotated with @test.
  2. Step 2: Check each option's syntax

    public function testExample() {} uses 'public function testExample() {}' which is correct PHP and Laravel style. Others are invalid PHP or wrong syntax.
  3. Final Answer:

    public function testExample() {} -> Option B
  4. Quick Check:

    Test methods = public function testName() [OK]
Hint: Test methods start with 'test' and are public functions [OK]
Common Mistakes:
  • Using wrong function visibility or missing 'public'
  • Using Python syntax in PHP tests
  • Incorrect function declaration order
3. Given this Laravel test method, what will be the test result?
public function testSum() {
    $a = 2;
    $b = 3;
    $this->assertEquals(5, $a + $b);
}
medium
A. Test throws a syntax error
B. Test fails because 2 + 3 does not equal 5
C. Test is skipped automatically
D. Test passes because 2 + 3 equals 5

Solution

  1. Step 1: Evaluate the sum in the test

    Variables $a and $b are 2 and 3, so $a + $b equals 5.
  2. Step 2: Check the assertion

    The assertion expects 5 and compares it to $a + $b, which is 5, so it matches and passes.
  3. Final Answer:

    Test passes because 2 + 3 equals 5 -> Option D
  4. Quick Check:

    2 + 3 = 5 passes assertion [OK]
Hint: Check math in assertEquals carefully [OK]
Common Mistakes:
  • Assuming test fails without checking values
  • Confusing assertEquals parameter order
  • Thinking syntax error without code issues
4. Identify the error in this Laravel unit test method:
public function testUserName() {
    $user = new User();
    $user->name = 'Alice';
    $this->assertEquals('Alice', $user->username);
}
medium
A. Property 'username' does not exist on User model
B. Missing semicolon after new User()
C. assertEquals parameters are reversed
D. Test method name does not start with 'test'

Solution

  1. Step 1: Check User model property usage

    The code sets $user->name but asserts $user->username, which likely does not exist.
  2. Step 2: Verify syntax and method name

    There is a semicolon after new User(), and method name starts with 'test', so no syntax or naming errors.
  3. Final Answer:

    Property 'username' does not exist on User model -> Option A
  4. Quick Check:

    Assert property exists before testing [OK]
Hint: Check property names match exactly in tests [OK]
Common Mistakes:
  • Assuming assertEquals parameters order causes error
  • Overlooking property name mismatch
  • Thinking method name is incorrect
5. You want to test a method that returns a list of active users from the database. Which approach best fits Laravel unit testing principles?
hard
A. Mock the User model's active() method and assert it returns expected data
B. Run the actual database query in the test without mocking
C. Test the method by printing results and checking manually
D. Skip testing because database queries are not testable

Solution

  1. Step 1: Understand unit test scope

    Unit tests isolate code parts, so database calls should be mocked to avoid external dependencies.
  2. Step 2: Evaluate options for best practice

    Mock the User model's active() method and assert it returns expected data mocks the User model's method and asserts expected results, fitting unit test principles. Run the actual database query in the test without mocking uses real DB, which is integration testing. Test the method by printing results and checking manually is manual and not automated. Skip testing because database queries are not testable is incorrect.
  3. Final Answer:

    Mock the User model's active() method and assert it returns expected data -> Option A
  4. Quick Check:

    Unit tests mock external calls [OK]
Hint: Mock external dependencies in unit tests [OK]
Common Mistakes:
  • Running real database queries in unit tests
  • Relying on manual output checks
  • Skipping tests for database-related methods