PHPUnit – Testing output of ‘echo’ or ‘print’

In this article, we will see how to test the output of echo or print.

In our previous articles, we have created a Calculator class with functionalities like sum, subtract and division. In this example, we will add another function called multiply.

The multiply function will take two arguments and prints its multiplied values using echo. We will test, the output of echo using PHPUnit.

1. Add function multiply to the class Calculator

<?php
    class Calculator{
        
        public function sum($n1, $n2){
            return $n1 + $n2;
        }

        public function subtract($n1, $n2){
            return $n1 - $n2;
        }

        public function divide($n1, $n2){
            if($n2 == 0)
                throw new InvalidArgumentException('Division by zero.');
            return $n1/$n2;
        }

        public function multiply($n1, $n2){
            echo $n1 * $n2;
        }
    }

2. Add PHPUnit code for testing output

<?php
    use PHPUnit\Framework\TestCase;

    class CalculatorTest extends TestCase {
        
        public function testIsSumCorrect(){
            $calc = new Calculator();
            $result = $calc->sum(1,2.5);
            $expected = 3.5;
            $this->assertSame($expected,$result);       
        }

        /**
        * @dataProvider subtractionProvider
        */        
        public function testIsSubtractionCorrect($n1, $n2, $expected){
            $calc = new Calculator();
            $result = $calc->subtract($n1,$n2);            
            $this->assertSame($expected,$result);       
        }
        

        /**
        *      @expectedException InvalidArgumentException
        */                
        public function testDivisionByZeroThrowsException(){
            $calc = new Calculator();
            $result = $calc->divide(1,0);            
        }

        public function testMultiplyPrintsOutput(){
            $expected = '50';
            $this->expectOutputString($expected);
            $calc = new Calculator();
            $calc->multiply(5,10);
        }
        

        public function subtractionProvider(){
            return [
                    "data1"=> [ 1 , 1 , 0],
                    "data2"=> [ -1 , 1 , -2],
                    "data3"=> [ 5 , 1 , 4],
                    "data4"=> [ 1 , 0.25 , 0.75]
            ];
        }
        

    }

3. Running the test

We can run the test by executing the given below command at the root of the project

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

Testing Output with PHPUnit

Comments on this post

No comments.

Leave a Reply

Your email address will not be published. Required fields are marked *

Trackbacks and Pinbacks on this post

No trackbacks.

TrackBack URL