1

I am starting to write phpUnit test and faced with such problem. 80% of my functions ending on such lines

    $data["res"] = $this->get_some_html($this->some_id);
    echo my_json_encode($data);
    return true;

How can i make test on such kind of functions in my classes?

4
  • Is there a reason you're just printing and not returning the value? Commented Mar 27, 2013 at 16:36
  • Ofc, i do AJAX response in a such way. Commented Mar 27, 2013 at 16:38
  • But why not just return the value and then print? Something like echo myFunction() instead of just calling myFunction()? Commented Mar 27, 2013 at 16:41
  • In anyway my function should ending on return true, this is the rule of our framework. If i write echo myFunction() layout will be true Commented Mar 27, 2013 at 16:45

1 Answer 1

3

You need to isolate your code into testable 'chunks'. You can test that the function returns TRUE/FALSE given specified text, and then test the JSON return data given fixed information.

function my_json_encode($data)
{
    return ...;
}

function get_some_html($element)
{
    return ...;
}

function element_exists($element)
{
    return ..;
}

function display_data($element)
{
    if(element_exists($element)
    {
        $data = get_some_html($element);
        $json = my_json_encode($data);
        return true;
    }
    else
    {
        return false;
    }
}    

Testing:

public function test_my_json_encode()
{
    $this->assertEquals($expected_encoded_data, my_json_encode($text));
}

public function test_get_some_html()
{
    $this->assertEquals($expected_html, get_some_html('ExistingElementId'));
}

public function test_element_exists()
{
    $this->assertTrue(element_exists('ExistingElementId');
    $this->assertFalse(element_exists('NonExistingElementId');
}

function test_display_data()
{
    $this->assertTrue(display_data('ExistingElementId'));
    $this->assertFalse(element_exists('NonExistingElementId');
}    

This is a simple, abstract example of the changes and the testing. As the comments above have indicated, you might want to change the return to be the JSON text, and a FALSE on error, then use === testing in your code to decide to display the text or not.

The next step would be to mock out the Elements, so you can get expected data without the need for a real HTML page.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.