PHPUnit Test to check module is enable or not in Magento 2?

You can write a unit test for your module’s common function to check Module enables or not from a system configuration setting.

Every Professional third party Module contains the Is Active/Is Enable feature for a module from System -> Configuration settings.

To Check module is enable or not, you can write a common function in Helper file or any Common files.

I have just created a Model file,
app/code/Rbj/UnitTestDemo/Model/ConfigData.php file,

In the above Model file, We have one function to check module is enable or not and we are checking using general function isModuleEnable().

Now We have to write a unit test for isModuleEnable() function using Magento 2,

When you need to write a Unit test for any file, you have to create a file structure like Test/Unit in your module root folder.

Filename suffix with Test. Our case name equals ConfigDataTest.php

We have to run a unit test in Model class,
app/code/Rbj/UnitTestDemo/Test/Unit/Model/ConfigDataTest.php
Our test that contains method testIsModuleEnable(),

When you write any test for specific function you must add the suffix “test” name before the function name.
Our test function name will be testIsModuleEnable().

Every Test file must extend \PHPUnit\Framework\TestCase

You can check above Test file with two methods.
1. setUp() method PHPUnit will automatically call it before each test run.
you can create the objects against which you will test.

setUp() run before all the testing methods inside of a test class. You can call the __construct() methods class argument inside setUp() method.

2. testIsModuleEnable function we have to test this function from our original Model file.
we need to create a Mock Object for scopeConfigInterface and set method as getValue() in the test case. original function call $this->scopeConfig->getValue().
With() takes the argument like constant and will() gives output for our ScopeInterface.

We have checked the assertTrue function to enable or disable result.

Now We can run the php unittest using the below command,
php vendor/bin/phpunit -c dev/tests/unit/phpunit.xml.dist app/code/Rbj/UnitTestDemo/Test/Unit/Model/ConfigDataTest.php

Output: