HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Unit-testing an adapter

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
adaptertestingunit

Problem

I want to create a class ClientSocket with PHP, which is an adapter of the fsockopen, fread, and fwrite.

Class ClientSocket extends SenderAdapterAbstract
{
    private $s = null;

    public function __construct($host, $port)
    {
        $this->s = fsockopen($host, $port);
    }

    // Abstract method concrete implementation
    public function send($message)
    {
        fwrite($this->s, $message);

        $result = fgets($this->s);
        fclose($this->s);
    }
}


Should I test this class? A unit test is not really one if it talks to the network.

Here is some rules about unit testing (I totally agree with them):

A test is not a unit test if:

  • It talks to the database



  • It communicates across the network



  • It touches the file system



  • It can't run at the same time as any of your other unit tests



  • You have to do special things to your environment (such as editing config files) to run it.

Solution

a unit test is not really one if it talks to the network...

I am not so sure what you meant by that. It seems like you are trying to follow exactly what someone may have said in a book or a talk. Unit testing is all about testing a 'Model'. And the assumptions are that the Model is isolated from any other models in the overall project.

In your case the Unit Test for the ClientSocket would be called ClientSocketTest.

Class ClientSocketTest extends PHPUnit_Testcase
{
    private $s = null;

    public function testSend()
    {
        $cs = new ClientSocket();
        $cs->send("My Message");
        $result = $cs->result;
        $this->assert("Everything's Good", $result);
    }
}


I noticed that your send method has the variable $result. For Unit Testing to be successful a method should return something. The purpose of Unit Testing is to see whether the given input gives you the expected output. Don't overcomplicate it!

Start with PHPUnit... and stick to it! :)

Code Snippets

Class ClientSocketTest extends PHPUnit_Testcase
{
    private $s = null;

    public function testSend()
    {
        $cs = new ClientSocket();
        $cs->send("My Message");
        $result = $cs->result;
        $this->assert("Everything's Good", $result);
    }
}

Context

StackExchange Code Review Q#38906, answer score: 3

Revisions (0)

No revisions yet.