如何为单元测试添加镜像?

时间:2014-11-03 作者:toy

我必须测试它调用的函数wp_get_attachment_image_src. 我如何添加一个用于测试的图像,因为现在如果我调用这个方法,它将返回false。

2 个回复
最合适的回答,由SO网友:J.D. 整理而成

我想看看WordPress是如何构建附件测试的。你会发现tests/phpunit/tests/post/attachments.php 他们使用this method:

function _make_attachment( $upload, $parent_post_id = 0 ) {

    $type = \'\';
    if ( !empty($upload[\'type\']) ) {
        $type = $upload[\'type\'];
    } else {
        $mime = wp_check_filetype( $upload[\'file\'] );
        if ($mime)
            $type = $mime[\'type\'];
    }

    $attachment = array(
        \'post_title\' => basename( $upload[\'file\'] ),
        \'post_content\' => \'\',
        \'post_type\' => \'attachment\',
        \'post_parent\' => $parent_post_id,
        \'post_mime_type\' => $type,
        \'guid\' => $upload[ \'url\' ],
    );

    // Save the data
    $id = wp_insert_attachment( $attachment, $upload[ \'file\' ], $parent_post_id );
    wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $upload[\'file\'] ) );

    return $this->ids[] = $id;

}
他们还included sample images 通过他们的测试。这里是an example of how they call the _make_attachment() method 在其中一项测试中:

function test_insert_image_no_thumb() {

    // this image is smaller than the thumbnail size so it won\'t have one
    $filename = ( DIR_TESTDATA.\'/images/test-image.jpg\' );
    $contents = file_get_contents($filename);

    $upload = wp_upload_bits(basename($filename), null, $contents);
    $this->assertTrue( empty($upload[\'error\']) );

    $id = $this->_make_attachment($upload);

    // ...
因此,您应该能够使用类似的方法为测试上传图像。您可以提供图像供自己使用,也可以只使用其中一个。

SO网友:James

如果您使用的是WordPress测试套件(您的测试类扩展了WP\\U UnitTestCase),那么您可以使用附带的工厂。

一、 e.如果您的测试在tests 可以创建的目录tests/assets/dummy-attachment.jpg

$post = $this->factory->post->create_and_get();
$attachment_id = $this->factory->attachment->create_upload_object( __DIR__ . \'/assets/dummy-attachment.jpg\', $post->ID );

结束

相关推荐

Load-Testing a Wordpress Site

有人能推荐WordPress的负载测试解决方案吗?我预计每月约有500000次页面点击,并希望对WP框架进行一些压力测试;服务器堆栈。我更喜欢开源的东西,但我对其他解决方案持开放态度。