Assignments On Class 35: Testing and Debugging PHP Code

Rashmi Mishra
0

 

Assignments On Class 35: Testing and Debugging PHP Code

Here are a few assignments based on the concepts of debugging and unit testing with PHPUnit for PHP. Each assignment includes step-by-step solutions and explanations.


Assignment 1: Debugging PHP Code

Problem:

You are given the following PHP code that is supposed to print a list of numbers from 1 to 10, but it's not working as expected. Your task is to debug the code and fix any errors.

php

Copy code

<?php

$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

 

foreach ($numbers as $number) {

    echo "The number is: " . $number . "<br>"

}

 

?>

Solution:

1.   Identifying the error:

o    There is a missing semicolon (;) after the echo statement in the foreach loop.

2.   Fixing the error:

o    Add a semicolon at the end of the echo statement.

php

Copy code

<?php

$numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

 

foreach ($numbers as $number) {

    echo "The number is: " . $number . "<br>";  // Added semicolon here

}

?>

3.   Explanation:

o    A missing semicolon after a statement is a syntax error in PHP. Once the semicolon is added, the code runs as expected and prints the numbers from 1 to 10.

4.   Output:

o    The code will now correctly display:

csharp

Copy code

The number is: 1

The number is: 2

The number is: 3

...

The number is: 10


Assignment 2: Writing a Unit Test Using PHPUnit

Problem:

You are tasked with testing a class called Calculator that has two methods: add($a, $b) and subtract($a, $b). Write PHPUnit test cases to check if these methods work correctly.

Class to be tested:

php

Copy code

<?php

class Calculator {

    public function add($a, $b) {

        return $a + $b;

    }

 

    public function subtract($a, $b) {

        return $a - $b;

    }

}

?>

Solution:

1.   Setting up PHPUnit:

o    First, install PHPUnit via Composer if you haven’t already.

o    Create a CalculatorTest.php file.

2.   Writing the Test Class:

o    The test class will contain methods to test both add() and subtract() methods.

php

Copy code

<?php

use PHPUnit\Framework\TestCase;

 

class CalculatorTest extends TestCase {

    public function testAdd() {

        $calc = new Calculator();

        $result = $calc->add(5, 10);

        $this->assertEquals(15, $result);  // Check if 5 + 10 equals 15

    }

 

    public function testSubtract() {

        $calc = new Calculator();

        $result = $calc->subtract(10, 5);

        $this->assertEquals(5, $result);  // Check if 10 - 5 equals 5

    }

}

?>

3.   Explanation:

o    We created a test class CalculatorTest that extends PHPUnit\Framework\TestCase.

o    Inside the test class, there are two test methods: testAdd() and testSubtract().

o    In testAdd(), we are calling the add() method with the parameters 5 and 10 and asserting that the result is 15.

o    In testSubtract(), we are calling the subtract() method with the parameters 10 and 5 and asserting that the result is 5.

4.   Running the Tests:

o    To run the tests, use the following command from your terminal:

bash

Copy code

./vendor/bin/phpunit --testdox CalculatorTest.php

5.   Output:

o    If the tests pass, you will see output similar to:

makefile

Copy code

CalculatorTest::testAdd

CalculatorTest::testSubtract

OK (2 tests, 2 assertions)


Assignment 3: Debugging and Testing a Calculator Class

Problem:

You are given a Calculator class that has a method divide($a, $b) which divides two numbers. However, the method has an error when dividing by zero. Fix the code and write PHPUnit tests to ensure the method works properly.

Class to be tested:

php

Copy code

<?php

class Calculator {

    public function divide($a, $b) {

        return $a / $b;  // Problematic when $b is 0

    }

}

?>

Solution:

1.   Fix the Divide Method:

o    We need to handle division by zero to avoid fatal errors.

php

Copy code

<?php

class Calculator {

    public function divide($a, $b) {

        if ($b == 0) {

            return "Error: Division by zero";  // Handle division by zero

        }

        return $a / $b;

    }

}

?>

2.   Writing Unit Test for divide():

php

Copy code

<?php

use PHPUnit\Framework\TestCase;

 

class CalculatorTest extends TestCase {

    public function testDivide() {

        $calc = new Calculator();

 

        // Test normal division

        $result = $calc->divide(10, 2);

        $this->assertEquals(5, $result);  // Expect 10 / 2 = 5

 

        // Test division by zero

        $result = $calc->divide(10, 0);

        $this->assertEquals("Error: Division by zero", $result);  // Expect error message

    }

}

?>

3.   Explanation:

o    In the divide() method, we check if $b is 0 before performing the division. If it is, we return an error message instead of performing the division.

o    In the test case, we verify two scenarios: one where division works normally and another where division by zero occurs.

4.   Running the Tests:

o    Run the tests with the following command:

bash

Copy code

./vendor/bin/phpunit --testdox CalculatorTest.php

5.   Output:

o    If the tests pass, you will see the following output:

bash

Copy code

CalculatorTest::testDivide

OK (1 test, 2 assertions)


Assignment 4: Debugging a PHP Function

Problem:

You have a function multiply($a, $b) that is supposed to return the product of two numbers, but it’s not working correctly. Find and fix the issue.

Faulty Code:

php

Copy code

<?php

function multiply($a, $b) {

    return $a * $b + 0;  // Incorrect operation

}

 

echo multiply(3, 4);  // Expected output: 12

?>

Solution:

1.   Identifying the Issue:

o    The issue with the code is that there's an unnecessary + 0 operation, which doesn't affect the result but makes the code confusing.

2.   Fixing the Code:

php

Copy code

<?php

function multiply($a, $b) {

    return $a * $b;  // Corrected to return the product of $a and $b

}

 

echo multiply(3, 4);  // Now it will correctly output 12

?>

3.   Explanation:

o    The + 0 in the original code doesn't change the result, but it made the code unnecessarily complicated. By removing it, the function now correctly returns the product of $a and $b.

4.   Output:

o    The code now correctly displays 12.


Conclusion

These assignments help students practice debugging common PHP issues and understanding how to write unit tests using PHPUnit to ensure their code behaves as expected. By solving these problems step by step, students will improve their debugging and testing skills, both of which are essential for writing clean, maintainable PHP code.

4o mini

You said:

give some more

ChatGPT said:

ChatGPT

Here are a few more assignments related to debugging PHP code and writing unit tests with PHPUnit:


Assignment 5: Debugging a PHP Function for String Manipulation

Problem:

You are given the following PHP code which is supposed to return the reversed version of a string. However, the code is not working properly. Your task is to debug it and fix the problem.

Faulty Code:

php

Copy code

<?php

function reverseString($string) {

    return strrev($string);

}

 

echo reverseString("Hello World") . "<br>";

echo reverseString("PHP") . "<br>";

?>

Solution:

1.   Identifying the Issue:

o    The code appears to be syntactically correct, and strrev() is the correct function to reverse a string in PHP. However, if the issue persists, it might be with the server or environment.

2.   Fixing the Error:

o    In case there's an environment issue, let's ensure that strrev() is being used properly. If it works locally but not on the server, investigate the PHP version or enable necessary extensions.

php

Copy code

<?php

function reverseString($string) {

    return strrev($string);  // Correct function for reversing the string

}

 

echo reverseString("Hello World") . "<br>";  // Output: dlroW olleH

echo reverseString("PHP") . "<br>";  // Output: PHP

?>

3.   Explanation:

o    The strrev() function is used to reverse a string in PHP. This assignment is meant to help students understand how simple string manipulation functions work in PHP.

4.   Output:

Copy code

dlroW olleH

PHP


Assignment 6: Write Unit Tests for a PHP Function

Problem:

Write unit tests using PHPUnit to verify the correctness of the following multiply() function. The function should return the product of two numbers.

Function:

php

Copy code

<?php

function multiply($a, $b) {

    return $a * $b;

}

?>

Solution:

1.   Write Unit Tests for multiply() Function:

php

Copy code

<?php

use PHPUnit\Framework\TestCase;

 

class MultiplyTest extends TestCase {

    public function testMultiplyPositiveNumbers() {

        $this->assertEquals(20, multiply(4, 5));  // 4 * 5 = 20

    }

 

    public function testMultiplyNegativeNumbers() {

        $this->assertEquals(12, multiply(-3, -4));  // -3 * -4 = 12

    }

 

    public function testMultiplyPositiveAndNegativeNumbers() {

        $this->assertEquals(-15, multiply(3, -5));  // 3 * -5 = -15

    }

 

    public function testMultiplyByZero() {

        $this->assertEquals(0, multiply(0, 10));  // 0 * 10 = 0

    }

}

?>

2.   Explanation:

o    We created a PHPUnit test class MultiplyTest to verify the functionality of the multiply() function.

o    Each test case checks a different scenario, including multiplying positive numbers, negative numbers, a positive and a negative number, and multiplying by zero.

3.   Running the Tests:

o    Use the following command to run the tests:

bash

Copy code

./vendor/bin/phpunit --testdox MultiplyTest.php

4.   Output:

o    If all tests pass, the output will show:

makefile

Copy code

MultiplyTest::testMultiplyPositiveNumbers

MultiplyTest::testMultiplyNegativeNumbers

MultiplyTest::testMultiplyPositiveAndNegativeNumbers

MultiplyTest::testMultiplyByZero

OK (4 tests, 4 assertions)


Assignment 7: Debugging a PHP Function for Factorial Calculation

Problem:

You are given the following PHP function that is supposed to calculate the factorial of a number. However, it’s not working as expected. Debug the function and fix the problem.

Faulty Code:

php

Copy code

<?php

function factorial($n) {

    if ($n == 0) {

        return 1;

    }

    return $n * factorial($n - 1);

}

 

echo factorial(5);  // Expected output: 120

?>

Solution:

1.   Identifying the Issue:

o    The code seems fine for calculating the factorial of a number. However, make sure that the input is valid and the base case is handled properly.

o    If the issue persists (like for negative numbers), we need to handle such cases where factorial for negative numbers is undefined.

2.   Fixing the Error:

o    Add input validation to ensure that $n is a non-negative integer.

php

Copy code

<?php

function factorial($n) {

    if ($n < 0) {

        return "Factorial not defined for negative numbers.";  // Added check for negative numbers

    }

    if ($n == 0) {

        return 1;

    }

    return $n * factorial($n - 1);

}

 

echo factorial(5);  // Expected output: 120

echo factorial(-3);  // Expected output: Factorial not defined for negative numbers.

?>

3.   Explanation:

o    The code recursively calculates the factorial of a given number. If the number is less than 0, it returns an error message indicating that the factorial is not defined for negative numbers.

4.   Output:

mathematica

Copy code

120

Factorial not defined for negative numbers.


Assignment 8: Debugging and Writing Unit Tests for an Array Sorting Function

Problem:

You are given the following sortArray() function that sorts an array in ascending order. There is a bug in the implementation, and the function is not returning the correct result. Debug the function and write unit tests for it.

Faulty Code:

php

Copy code

<?php

function sortArray($arr) {

    sort($arr);  // Sorting function should work fine, but an issue exists

    return $arr;

}

 

$numbers = [5, 1, 3, 7, 9];

echo implode(",", sortArray($numbers));  // Expected output: 1,3,5,7,9

?>

Solution:

1.   Identifying the Issue:

o    The function uses PHP’s built-in sort() function, which sorts arrays in-place and does not return the sorted array directly.

o    The issue here is that sort() modifies the array and returns a boolean (true or false), not the sorted array.

2.   Fixing the Error:

o    We need to return the sorted array after calling sort().

php

Copy code

<?php

function sortArray($arr) {

    sort($arr);  // Sorts the array in-place

    return $arr;  // Returns the sorted array

}

 

$numbers = [5, 1, 3, 7, 9];

echo implode(",", sortArray($numbers));  // Expected output: 1,3,5,7,9

?>

3.   Writing Unit Test for sortArray():

php

Copy code

<?php

use PHPUnit\Framework\TestCase;

 

class SortArrayTest extends TestCase {

    public function testSortArray() {

        $result = sortArray([5, 1, 3, 7, 9]);

        $this->assertEquals([1, 3, 5, 7, 9], $result);  // Check if the array is correctly sorted

 

        $result = sortArray([10, 4, 8, 2]);

        $this->assertEquals([2, 4, 8, 10], $result);  // Check another case

    }

}

?>

4.   Explanation:

o    The sortArray() function is now correctly returning the sorted array after calling sort().

o    We also created a PHPUnit test case to verify that the array is sorted correctly in multiple scenarios.

5.   Running the Tests:

o    Run the tests with the following command:

bash

Copy code

./vendor/bin/phpunit --testdox SortArrayTest.php

6.   Output:

o    If the tests pass, the output will show:

bash

Copy code

SortArrayTest::testSortArray

OK (1 test, 2 assertions)


Assignment 9: Debugging a PHP Code for String Replacement

Problem:

You are given the following PHP code that replaces all occurrences of "apple" with "orange" in a string. However, the replacement is not happening correctly. Debug the code and fix the issue.

Faulty Code:

php

Copy code

<?php

function replaceAppleWithOrange($str) {

    return str_replace('apple', 'orange', $str);  // Not replacing 'apple' correctly

}

 

echo replaceAppleWithOrange('I have an apple in my basket.');

?>

Solution:

1.   Identifying the Issue:

o    The issue here could be a case sensitivity problem. The string 'apple' is case-sensitive by default in str_replace().

2.   Fixing the Error:

o    We can make the replacement case-insensitive by passing true as the fourth argument.

php

Copy code

<?php

function replaceAppleWithOrange($str) {

    return str_ireplace('apple', 'orange', $str);  // Using case-insensitive replacement

}

 

echo replaceAppleWithOrange('I have an apple in my basket.');

echo replaceAppleWithOrange('I have an Apple in my basket.');

?>

3.   Explanation:

o    The str_ireplace() function performs a case-insensitive search and replace, solving the problem of case sensitivity.

4.   Output:

css

Copy code

I have an orange in my basket.

I have an orange in my basket.


These assignments will help students improve their PHP debugging and testing skills while also enhancing their understanding of PHP functions and unit testing with PHPUnit.


Post a Comment

0Comments

Post a Comment (0)