I want to test socket connection.
socket connection code:
if (!socket_connect($this->socket, $this->getConfig('host'), $this->getConfig('port'))) {
throw new ConnectionException("Connection failed: " . $this->getLastError());
}
Test method:
<?php
require_once '../Webservice.php';
require_once '../Exception/ConnectionException.php';
class WebserviceTest extends PHPUnit_Framework_TestCase
{
/**
* @expectedException ConnectionException
* @expectedExceptionMessageRegExp #Connection failed:.*#
*/
public function testWebserviceConnectionException()
{
$config = array(
'host' => '127.0.0.1',
'port' => '23'
);
new Webservice($config);
}
}
In my application everything works fine I've ConnectionException but in phpunit I have:
Failed asserting that exception of type "PHPUnit_Framework_Error_Warning" matches expected exception "ConnectionException". Message was: "socket_connect(): unable to connect [111]: Connection refused".
How I have to test this exception? I'm newbie in phpunit and testing ;(
I think you should use non-blocking socket to avoid the warning:
This way,
socket_connect()
should return false, and not a warning, and the exception will be catch by phpunit.