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.
JavaScript
x
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
JavaScript
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
JavaScript
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
JavaScript
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,
JavaScript
$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
JavaScript
$local = new ip_request();
$this->assertEquals('127.0.0.1', $local->getRealIpAddr());