简体   繁体   中英

PhpUnit check output text

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM