How to get ScopeConfigInterface through the object manager of unit tests in magento 2?
I may be wrong here, but I think for unit tests you don't have to retrieve values from the data base. You can assume that the implementations of \Magento\Framework\App\Config\ScopeConfigInterface
are tested and work properly.
You only have to test your method that uses getValue
from the ScopeConfigInterface
.
For example, if you have a method like this:
public function getSomeConfigValue()
{
return $this->scopeConfig->getValue('some/path/here', ScopeInterface::SCOPE_STORE)
}
you need to test that method only and not if the value from the db is what you need.
and you can test that like this:
public function testGetSomeConfigValue()
{
$dbValue = 'dummy_value_here';
$scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class)
->disableOriginalConstructor()
->getMock();
$scopeConfigMock->method('getValue')
->willReturn($dbValue);
$objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
$myClass = $objectManager->getObject(
\Your\Class\Name\Here::class,
[
'scopeConfig' => $scopeConfigMock,
..., //your other mocked dependencies here
]
);
$this->assertEquals($dbValue, $myClass->getSomeConfigValue());
}
Depending on the number of dependencies that have to be injected into the constructor, you might not even have to use the unit test ObjectManager, but can simply instantiate the class under test directly using new
.
$myClass = new \Your\Class\Name\Here($scopeConfigMock);
This is simpler and as such preferable for unit tests. The only reason to use the unit test object manager is if a large number of dependencies makes mocking each one manually too cumbersome.