Skip to content
Advertisement

How to get PHPUnit testing working with a function that returns an IP?

I’m just new to TDD and I’ve installed PHPUnit with PhpStorm.

I have this class and function, and I want to test for the IP address match.

class ip_request
{

    function getRealIpAddr()
    {
        if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
        {
            $ip=$_SERVER['HTTP_CLIENT_IP'];
        }
        elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
        {
            $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        else
        {
            $ip=$_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }
}

I’m trying to create the code for the test, and I’m not sure what to put in.

I have tried

public function testGetRealIpAddr()
    {
        
        $expected = '127.0.0.1';
        $this->assertEquals($expected, $test);
    }

But $test is undefined obviously.

What should I do next?

Tried suggestion given

public function testGetRealIpAddr()
    {
        $UserIpAddress = $this
            ->getMockBuilder('ip_request')
            ->getMock();

        $UserIpAddress->expects($this->once())
            ->method('getRealIpAddr')
            ->willReturn('127.0.0.1'); // Set ip address whatever you want to use
    }

But the error I get now is that

Trying to configure method "getRealIpAddr()" which cannot be configured because it does not exist, has not been specified, is final, or is static

Advertisement

Answer

I fixed this similarly to how @hakre suggested,

$ip = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';

I added ?? '127.0.0.1' to the end of that statement, and that fixed it.

Also just updated my test function to show only

 $local = new ip_request();
 $this->assertEquals('127.0.0.1', $local->getRealIpAddr());
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement