============ Unit-Testing ============ PHP unit testing ---------------- Getting PHPUnit ^^^^^^^^^^^^^^^ Nextcloud uses PHPUnit >= 8.5 for unit testing. PHPUnit documentation: https://phpunit.de/documentation.html Writing PHP unit tests ^^^^^^^^^^^^^^^^^^^^^^ To get started, do the following: - Create a directory called ``tests`` in the top level of your application - Create a PHP file in the directory and ``require_once`` your class which you want to test Then you can simply run the created test with **phpunit**. .. note:: If you use Nextcloud functions in your class under test (i.e., OC::getUser()) you'll need to bootstrap Nextcloud or use dependency injection. .. note:: You'll most likely run your tests under a different user than the Web server. This might cause problems with your PHP settings (i.e., open_basedir) and requires you to adjust your configuration. An example for a simple test would be: :file:`/srv/http/nextcloud/apps/myapp/tests/testaddtwo.php` .. code-block:: php testMe = new \OCA\Myapp\TestMe(); } public function testAddTwo(){ $this->assertEquals(5, $this->testMe->addTwo(3)); } } :file:`/srv/http/nextcloud/apps/myapp/lib/testme.php` .. code-block:: php `_ test runner with `Jasmine `_. Installing Node JS ^^^^^^^^^^^^^^^^^^ To run the JavaScript unit tests you will need to install **Node JS**. You can get it here: https://nodejs.org/ After that you will need to setup the **Karma** test environment. The easiest way to do this is to run the automatic test script first, see next section. Running all tests ^^^^^^^^^^^^^^^^^ To run all tests, just run:: ./autotest-js.sh This will also automatically set up your test environment. Debugging tests in the browser ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To debug tests in the browser, you need to run **Karma** in browser mode:: karma start tests/karma.config.js From there, open the URL http://localhost:9876 in a web browser. On that page, click on the "Debug" button. An empty page will appear, from which you must open the browser console (F12 in Firefox/Chrome). Every time you reload the page, the unit tests will be relaunched and will output the results in the browser console. Unit test paths ^^^^^^^^^^^^^^^ JavaScript unit test examples can be found in :file:`apps/files/tests/js/`. Unit tests for the core app JavaScript code can be found in :file:`core/js/tests/specs`. Documentation ^^^^^^^^^^^^^ Here are some useful links about how to write unit tests with Jasmine and Sinon: - Karma test runner: https://karma-runner.github.io/ - Jasmine: https://pivotal.github.io/jasmine - Sinon (for mocking and stubbing): http://sinonjs.org/