WordPress plugin phpunit tests with dependencies

馋奶兔 提交于 2019-12-10 23:30:54

问题


I suspect this would be a duplicate question or something with a very simple answer, but I've searched on every term I can come up with without any result.

It's really simple; How can I unit test WordPress plugins that depends on other plugins?

I'm currently working on a WooCommerce plugin which will contain a payment gateway, which has to extend the WC_Payment_Gateway included in the WooCommerce plugin. So I need WordPress to load and activate WooCommerce. I tried;

  1. manually just including /plugins/woocommerce/woocommerce.php. Gives me db errors as WooCommerce tables has not been created.
  2. running activate_plugin( '<woocommerce plugin path>' ); on the "muplugins_loaded" action. Gives same error as above.
  3. Cloning WooCommerce dev. repo and including test/bootstrap.php in woocommerce. Gives me a PHP fatal error: wp-content/plugins/woocommerce/tmp/wordpress-tests-lib/includes/functions.php): failed to open stream: No such file or directory in /home/...
  4. Running /plugins/woocommerce/tests/bin/install.sh. Gives me PHP Fatal error: Cannot redeclare tests_add_filter() (previously declared in ...
  5. Combinations of the above

Anyone know what I'm doing wrong? I really don't want to drop unit tests but currently seems like the only option as I'm getting fatal b/c some classes in my plugin i.e. type hint the payment gateway which obviously forces the autoloader to get it.

Thanks in advance :)


回答1:


I ended up creating "Dependency substitution" (mock) classes in a special folder that is only registered to the autoloader in the test environment (not dev/prod to prevent collisions with the real classes).

I think it's a really ugly solution as the tests will pass even if the api that we depend on changes and breaks the application - breaks the whole point of doing unit tests imo. But you know.. All is fair in love and war lol




回答2:


I just spent hours trying to figure this out, and got there eventually. Leaving this answer here for anyone else that's looking.

This guide explains the process quite well: https://wptheming.com/2016/01/unit-tests-for-woocommerce-extensions/

Basically you can copy the entire woocommerce test suite into your extension folder and make a few adjustments to the initialization in the bootstrap file, so that you load up woocommerce and your extension together.



来源:https://stackoverflow.com/questions/33099494/wordpress-plugin-phpunit-tests-with-dependencies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!