【问题标题】:How would you PHPUnit test a Wordpress function containing get_post_meta()?您将如何 PHPUnit 测试包含 get_post_meta() 的 Wordpress 函数?
【发布时间】:2017-09-21 10:00:40
【问题描述】:

我刚刚开始使用 Wordpress 学习 PHPUnit。我有一个小部件,可以从中获取发布数据和元数据。

我的代码如下所示:

           if ($postMeta = get_post_meta($post->ID, 'feature_news_colours_overlay')) {
                $colourOverlay = $postMeta['0'];
            }
          $items[] = [
                'title' => $title,
                'url' => get_permalink($post->ID),
                'description' => $content,
                'colourOverlay' => $colourOverlay,
            ];

小部件正在从feature_news_colours_overlaycustom_field 获取帖子的数据。在我的 PhpUnit 测试中,我可以添加以下内容来测试 if 条件。

          $post = new \stdClass();
          $post->post_title = 'Some title text to test.';
          $post->ID = 1;
          $GLOBALS['post_meta'][0] = '#FFCC00'; 

这实际上用断言测试了我的 Item 数组:

'title' => 'Some title text to test.',
'url' => 'http://something..',
'description' => 'test desc',
'colourOverlay' => '#FFoooo'

这实际上测试了我的 if 条件,因为我发现这不是标准方法,如果我必须检查超过 1 个我无法使用 GLOBAL 值实际测试的帖子。

$GLOBALS['post_meta'][0] = '#FFCC00';

有什么办法可以给每篇文章添加一个模拟元值来检查 if 条件吗?

【问题讨论】:

    标签: php wordpress unit-testing phpunit


    【解决方案1】:

    如果您将要测试的帖子 ID 放入 $post_id,则

    add_post_meta( $post_id, 'your_meta_key', 'your_test_value' ); 
    

    在您的断言之前的测试代码中应该可以解决问题。

    【讨论】:

      猜你喜欢
      • 2016-12-19
      • 2013-08-02
      • 1970-01-01
      • 2016-09-21
      • 2012-10-19
      • 2015-08-21
      • 2015-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多