How to do an unit test for the admin dashboard

There are basically three options:

  1. Load that file with the admin-side code on-the-fly in setUp() or setUpBeforeClass(), so it will be loaded when those tests run.
  2. Load that file before the test suite is loaded and run, like in a bootstrap.php file or something, so it will be loaded for all the tests.
  3. Separate your tests into several different test suites, some that run as if is_admin(), and some that do not. (Or, always run the tests as if is_admin(), similar to your suggestion with using a plugin.)

Of these three, I have done both of the first two when testing my plugins. #2 is really the easiest, since you just load that file once and then forget it, you don’t have to make sure that every testcase that relates to the code from that file included the file in setUpBeforeClass().

The only downside to #1 and #2, is that they circumvent your plugin’s logic that normally determines when this code is loaded. So in your tests you are testing the code in that file, but you aren’t testing that your plugin is actually loading that file properly.

This is OK, if we are talking about unit tests. Unit tests are about testing the individual units of your code, like each of the different aspects of each function contained in that file. They aren’t really about ensuring that your plugin operates properly as a whole. Since you are using Codeception, you can also run functional and acceptance tests, in addition to unit tests. In your function and acceptance tests is where you will test that your plugin operates properly as a whole, which includes (indirectly) testing that that admin-side code is loaded in the admin.

So, I would just load the file in setUpBeforeClass() or in bootstrap.php or the like, and not worry about this in my unit tests. In your acceptance tests, when you test how your plugin actually operates within the WordPress dashboard via the browser, you will be testing that the admin-side code is being loaded when it should.

It might be possible to do #3 for the unit tests, but basically your acceptance tests are already doing this: when you have the browser visit your plugin’s UI within the admin to test it, your test will fail if the admin-side code isn’t being loaded when it should.