Adding Unit Tests to an Existing WordPress Plugin

Adding Unit Tests to an Existing WordPress Plugin

So far we’ve accomplished little greater than introduce you to the thought of constructing assessments on your WordPress plugins and speak about a bunch of the additional phrases you want to perceive to dive deeper into testing your code. Today we’re going to make it sensible by grabbing considered one of my free plugins and including a number of unit assessments to present you the way to put it collectively. 

You can discover the plugin on Github or WordPress.org. Just like my earlier put up, I assume that you’ve got WP CLI put in and might arrange fundamental assessments. If you’ll be able to’t try my put up introducing you to unit testing in WordPress.

Unlike the final time, we solely want to scaffold the assessments so we will begin with the next command in our WordPress set up.

wp scaffold plugin-tests wptt-ics-feeds

Now let’s get into writing a number of assessments.

The very first thing I need to take a look at is to be sure that the hyperlinks a person sees of their profile with calendar feeds are appropriate. Specifically, we’re going to have a look at the get_subscribe_link operate.

You can see the finished assessments for this part here.

Let’s begin by copying the default pattern take a look at file and renaming it to test-feed-links.php. I all the time like to create totally different information for the areas of the plugins I’m writing assessments for, even when which means I’ve a number of information to cope with. It’s far simpler to keep organized with clearly labelled information.

This plugin is a bit older and instantiates a worldwide variable because it begins up. This permits us to name that international when in our setUp operate in order that we have now entry to the plugin code. We’ll additionally want to use the WordPress Factory to arrange a brand new person in order that we will take a look at the hyperlinks supplied with that person. That means our setUp and tearDown capabilities ought to appear to be this.

public operate setUp(){

    dad or mum::setUp();

    // getting the plugin international

    $this->plugin = $GLOBALS['wptt_ics_feeds'];

    // make a faux person

    $this->editor = new WP_User( $this->factory->user->create( array( 'function' => 'editor' ) ) );

}

public operate tearDown(){

        dad or mum::tearDown();

        wp_delete_user( $this->editor->ID, true );

}

Now we will get to writing a take a look at for our feed hyperlinks. We’ll write two totally different assessments to take a look at each conditions that the hyperlink operate can discover itself in. First, we’ll take a look at get_subscribe_link() with none arguments.

   /**

     * Tests base feed hyperlink with out writer

     */

    public operate test_base_feed_link(){

        $feed_link = $this->plugin->get_subscribe_link();

        $complete_link = site_url() . '/?feed=wptticsfeeds';

        $this->assertEquals( $feed_link, $complete_link, 'The feed hyperlinks are usually not equal' );

    }

The very first thing the code above does is entry our plugin occasion as outlined within the setUp operate and name the get_subscribe_link() operate. Next, I laborious code the anticipated output of the operate in order that I’ve one thing to examine in opposition to. Finally, we use assertEquals to examine the 2 values.

With that accomplished I can head again over to terminal and run the assessments with the phpunit command. If my assessments go I’ll see one thing just like the output under. If they don’t go then I’ll get a giant crimson warning as an alternative of a inexperienced bar, which suggests I would like to determine why they aren’t passing and repair the assessments.

Adding Unit Tests to an Existing WordPress Plugin JowqGqghL27hojsCkyZM9fbkln dlJfVdg0uSe6TX3ilDyn5d2zoKjssaYVNNmciP old3wiBld1 NyIp4r

In this case, our assessments handed and we will transfer on to testing the output of our hyperlink operate if we go in an writer title. You can see this take a look at under.

   /**

     * Tests feed hyperlink with writer

     */

     public operate test_author_feed_link(){

        $feed_link = $this->plugin->get_subscribe_link( array( 'writer' => $this->editor->ID ) );

        $complete_link = esc_url( site_url() . '/?feed=wptticsfeeds&wpttauthor=". $this->editor->user_login );

        $this->assertEquals( $feed_link, $complete_link, "The feed hyperlinks with writer are usually not equal' );

     }

Here we do nearly the identical factor as we did after we examined our hyperlink beforehand. The change is that we go within the person we created with our setUp operate after which take a look at to be sure that this hyperlink comes out as anticipated with assertEquals.

Now, let’s transfer on to testing the customized filter contained in the plugin.

Testing a WordPress Filter with PHPUnit

I’ve had some disputes with different builders about testing filters previously. Some don’t trouble testing their inside plugin filters, however I feel that try to be testing these filters. Sometimes filter names change and also you overlook about this so don’t doc it anyplace or verify for utilization of the filter. Writing a easy take a look at on your filter will spotlight this as a result of if you change the filter title a take a look at error will occur.

For this take a look at, we’ll add a brand new file to our assessments folder known as test-filters.php. I’ll use this file to take a look at all future filters that want to be examined within the plugin. This time our setUp operate solely wants to instantiate an occasion of our plugin and our tearDown operate doesn’t want to do something. See the code under.

   public operate setUp(){

        dad or mum::setUp();

        // getting the plugin international

        $this->plugin = $GLOBALS['wptt_ics_feeds'];

    }

    public operate tearDown(){

        dad or mum::tearDown();

    }

Next, we want to write the take a look at for our filter which you’ll be able to see under.

   /**

     * Tests that the put up the place time could be modified with a filter

     */

    public operate test_posts_where_filter(){

        add_filter( 'wptt_ics_feeds_how_old', array( $this, 'new_where' ), 10, 2 );

         $output = $this->plugin->two_months( '' );

         $date = date('Y-m-d', strtotime( $this->new_where() ) );

         $this->assertStringContainsString( $date, $output, 'The date filter didn't work' );

    }

    public operate new_where(){

        return '-1 week';

    }

The very first thing we do is name our filter after which go it our new_where operate. I all the time like to write a separate operate for filter assessments as a result of I’ve ended up utilizing them in a number of assessments sufficient that I really feel this protects work later. Our new_where operate will go the string -1 week to our filter.

Next we name our two_months() operate contained in the plugin. Then we use a normal PHP date operate to get the format we anticipate for the date. Since I’m principally involved that the date is parsed correctly within the plugin I exploit assertStringContainsString to verify to see if the output of the two_months operate incorporates the identical date string because the $date variable.

Again, in case your assessments go, then it ought to all be inexperienced. If they fail you’ll get a giant crimson warning as an alternative of the nice inexperienced bar.

Why Don’t We Test the ICS Feed Output

Note, that I didn’t take a look at the ultimate output of our ICS feed. While that is attainable, it’s acquired a bunch of transferring elements that might fail and don’t have anything to do with my code. I might ship the ICS feed to an on-line validator after which obtain the JSON response and parse it to verify if it’s legitimate.

If the HTTP request fails, my take a look at fails. If the web validation service shuts down, my take a look at fails. There are a bunch of different eventualities that might additionally trigger my take a look at to fail for no motive that’s my fault. Because of this, I selected not to take a look at the ultimate feed programmatically and figured that I might take a look at it by subscribing to a feed in my calendar and seeing that my posts have been in actual fact on the calendar as anticipated.

This Isn’t Unit Testing

I’m positive that a few of you’re looking at this and saying that I’m not writing unit assessments, and also you’d be appropriate. I’m writing integration assessments as a result of my code is integrating with WordPress for the assessments to work. Yes, you need to use WP_Mock to faux WordPress to write true unit assessments, however more often than not I care that my code works with WordPress.

Today, we checked out including a number of assessments to an present WordPress plugin as a sensible instance of how testing can work on your initiatives. To proceed studying, try the enterprise case for including testing to your course of as a enterprise proprietor. It could be laborious to see previous the upfront expense since improvement will take longer, however it does repay.

Check Also

How to Create an Engaging Job Description for DevOps Engineer Positions

Introduction: In at present’s quickly evolving technological panorama, companies are more and more recognizing the …