diff --git a/tests/phpunit/includes/factory/class-wp-unittest-factory-for-attachment.php b/tests/phpunit/includes/factory/class-wp-unittest-factory-for-attachment.php index 262c6c4640790..989275879df1c 100644 --- a/tests/phpunit/includes/factory/class-wp-unittest-factory-for-attachment.php +++ b/tests/phpunit/includes/factory/class-wp-unittest-factory-for-attachment.php @@ -61,8 +61,17 @@ public function create_object( $args, $legacy_parent = 0, $legacy_args = array() * @return int|WP_Error The attachment ID on success, WP_Error object on failure. */ public function create_upload_object( $file, $parent_post_id = 0 ) { - $contents = file_get_contents( $file ); - $upload = wp_upload_bits( wp_basename( $file ), null, $contents ); + $contents = file_get_contents( $file ); + $upload_dir = wp_upload_dir(); + $file_basename = wp_basename( $file ); + $file_path = $upload_dir['path'] . '/' . $file_basename; + + // Remove existing file if it exists. + if ( file_exists( $file_path ) ) { + unlink( $file_path ); + } + + $upload = wp_upload_bits( $file_basename, null, $contents ); $type = ''; if ( ! empty( $upload['type'] ) ) {