I'm new to unit testing, but I think I understand the basics. I want to unit test a fairly simple class. (See below) I have a problem when setting up the because I don't know how to handle stream_socket_client()
. I read that I should inject dependencies, but I think this would only relocate the problem with stream_socket_client()
to the class injecting the client into the class ExampleProcessor
as shown below.
<?php namespace App;
use Exception;
class ExampleProcessor
{
private $client;
private $result;
public function __construct()
{
$this->client = stream_socket_client(
"tcp://"
. gethostbyname($_ENV['PROCESSOR_HOST'])
. ":"
. $_ENV['PROCESSOR_PORT'],
$errno,
$errorMessage
);
if ($this->client === false) {
throw new Exception();
}
}
public function process($data)
{
$result = fwrite($this->client, $data);
if ($result === false) {
throw new Exception();
}
$this->result = stream_get_contents($this->client);
if ($this->result === false) {
throw new Exception();
}
fclose($this->client);
}
public function getResult()
{
return json_decode($this->result);
}
}
What would be a good approach to test this class?