0
0
Laravelframework~10 mins

Unit tests in Laravel - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a basic unit test class in Laravel.

Laravel
<?php

namespace Tests\Unit;

use PHPUnit\Framework\TestCase;

class ExampleTest extends TestCase
{
    public function testBasicTest()
    {
        $this->assertTrue([1]);
    }
}
Drag options to blanks, or click blank then click option'
ATrue
Btrue
C1
Dfalse
Attempts:
3 left
💡 Hint
Common Mistakes
Using uppercase True instead of lowercase true.
Passing false or 1 instead of true.
2fill in blank
medium

Complete the code to run a test that checks if two values are equal.

Laravel
public function testValuesAreEqual()
{
    $expected = 5;
    $actual = 2 + 3;
    $this->assert[1]($expected, $actual);
}
Drag options to blanks, or click blank then click option'
ASame
BEqual
CEquals
DEqualTo
Attempts:
3 left
💡 Hint
Common Mistakes
Using assertEqual which does not exist.
Using assertSame which is stricter than needed.
3fill in blank
hard

Fix the error in the test method to correctly check if a string contains a substring.

Laravel
public function testStringContains()
{
    $string = 'Laravel Framework';
    $this->assertStringContainsString([1], $string);
}
Drag options to blanks, or click blank then click option'
A'framework'
B'Framework'
C'laravel'
D'Laravel'
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase 'framework' which does not match the case.
Using lowercase 'laravel' instead of 'Laravel'.
4fill in blank
hard

Fill both blanks to create a test that expects an exception to be thrown.

Laravel
public function testException()
{
    $this->expectException([1]::class);
    throw new [2]();
}
Drag options to blanks, or click blank then click option'
A\InvalidArgumentException
B\Exception
C\RuntimeException
D\LogicException
Attempts:
3 left
💡 Hint
Common Mistakes
Using different exception classes in the expect and throw statements.
Omitting the leading backslash in the class name.
5fill in blank
hard

Fill all three blanks to write a test that mocks a class method and asserts it was called once.

Laravel
public function testMockMethodCall()
{
    $mock = $this->createMock([1]::class);
    $mock->expects($this->once())
         ->method([2])
         ->willReturn([3]);
    
    $result = $mock->process();
    $this->assertEquals('done', $result);
}
Drag options to blanks, or click blank then click option'
AApp\Services\Processor
B'process'
C'done'
DApp\Models\User
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong class names for mocking.
Passing method name without quotes.
Returning a value that does not match the assertion.