jeudi 23 avril 2015

How to test this class or rewrite it to be testable? phpspec

This class is fairly simple, it adds a twitter hashtag to a string if there is room for it. Twitter only allows 140 characters (minus 23 for a url). So the hashtags keep getting added if there is space for one.

I don't think it's 100% working as expected, but that is not relevant to my question which is located below.

class Hashtags {

private $url_character_count = 23;
private $characters_allowed = 140;

public function __construct(Article $article)
{
    $this->article = $article;
    $this->characters_remaining = $this->characters_allowed - $this->url_character_count;
}

public function createHashtagString()
{
        $hashtags = '';
        $hashtags .= $this->addEachNodeHashtag();
        $hashtags .= $this->addHashtagIfSpace($this->article->topic_hashtag);
        $hashtags .= $this->addHashtagIfSpace($this->article->pubissue_hashtag);
        $hashtags .= $this->addHashtagIfSpace($this->article->subject_area_hashtag);
        $hashtags .= $this->addHashtagIfSpace('#aviation');
        return $hashtags;
}

private function addEachNodeHashtag()
{
    //Returns a hashtag or calls hashtagString() if it is a comma separated list
}

private function hashtagString()
{
    //Explodes a comma seperated string of hashtags and calls addHashtagIfSpace()

}

private function addHashtagIfSpace($hashtag_string)
{
    if((strlen($hashtag_string) + 1) <= $this->characters_remaining)
    {
        $this->characters_remaining = $this->characters_allowed - $this->characters_remaining;

        if(empty($hashtag_string))
        {
            return '';
        }

        return ' ' . $hashtag_string;
    }
}

}

Here is my test, my problem is that this only tests one specific case, where all the fields are filled in, and when there is enough space to fit them all. Should I just keep making a bunch of these test functions for different cases? I am guessing there will be about 10 of them. I have never done testing before, so I am a bit out of my element and need to to pointed in the correct direction.

Thank you

class HashtagsSpec extends ObjectBehavior
{

function it_creates_hashtag_string_with_all_fields_filled_in(Article $article)
{
    $this->beConstructedWith($article);
    $article->title = 'This is the article title';
    $article->url = 'http://ift.tt/1d4JycA';
    $article->pubissue_hashtag = '#AHASHTAG';
    $article->subject_area_hashtag = '#SUBAREA';
    $article->topic_hashtag = '#TOPIC';
    $article->node_hashtags = '#Test1,#Test2,#Test3';

    $this->createHashtagString()->shouldReturn(' #Test1 #Test2 #Test3 #TOPIC #AHASHTAG #SUBAREA #aviation');

}
}

Aucun commentaire:

Enregistrer un commentaire