I have to test the function where it calls wp_get_attachment_image_src. How do I add an image for testing, because right now if I call this method it returns false.

  • When I've testing suites for WordPress, like any other system, you often need to create mock results for methods that would otherwise hit the database or file system, this is no different. WordPress itself includes a damn good built in set of tests, so you can trust that most of the code within the cms itself is solid enough for mocks to rely on. Nov 3, 2014 at 17:51

2 Answers 2


I'd take a look at how WordPress has constructed their attachment tests. You'll find that tests/phpunit/tests/post/attachments.php they use 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;


They've also included sample images with their tests. Here is an example of how they call the _make_attachment() method in one of their tests:

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 you should be able to use something like that to upload an image for your test. You could supply the image to use yourself, or just use one of those already included.


If you're using the WordPress testing suite (your test classes extend WP_UnitTestCase), you can use the included factory.

I.e. if your tests are in a tests directory you could create 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 );

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.