I'm writing a unit test for a class method that calls another class's method using a mock, only the method that needs to be called is declared as final, so PHPUnit is unable to mock it. Is there a different approach I can take?
example:
class to be mocked
class Class_To_Mock
{
final public function needsToBeCalled($options)
{
...
}
}
my test case
class MyTest extends PHPUnit_Framework_TestCase
{
public function testDoSomething()
{
$mock = $this->getMock('Class_To_Mock', array('needsToBeCalled'));
$mock->expects($this->once())
->method('needsToBeCalled')
->with($this->equalTo(array('option'));
}
}
Edit: If using the solution provided by Mike B and you have a setter/getter for the object you're mocking that does type checking (to ensure the correct object was passed into the setter), you'll need to mock the getter on the class you're testing and have it return the other mock.
example:
class to be mocked
class Class_To_Mock
{
final public function needsToBeCalled($options)
{
...
}
}
mock
class Class_To_MockMock
{
public function needsToBeCalled($options)
{
...
}
}
class to be tested
class Class_To_Be_Tested
{
public function setClassToMock(Class_To_Mock $classToMock)
{
...
}
public function getClassToMock()
{
...
}
public function doSomething()
{
$this->getClassToMock()
->needsToBeCalled(array('option'));
}
}
my test case
class MyTest extends PHPUnit_Framework_TestCase
{
public function testDoSomething()
{
$classToTest = $this->getMock('Class_To_Be_Tested', array('getClassToMock'));
$mock = $this->getMock('Class_To_MockMock', array('needsToBeCalled'));
$classToTest->expects($this->any())
->method('getClassToMock')
->will($this->returnValue($mock));
$mock->expects($this->once())
->method('needsToBeCalled')
->with($this->equalTo(array('option'));
$classToTest->doSomething();
}
}
I don't think PHPUnit supports stubbing/mocking of final methods. You may have to create your own stub for this situation and do some extension trickery:
class myTestClassMock {
public function needsToBeCalled() {
$foo = new Class_To_Mock();
$result = $foo->needsToBeCalled();
return array('option');
}
}
Found this in the PHPUnit Manual under Chapter 11. Test Doubles
Limitations
Please note that final, private and static methods cannot be stubbed or mocked. They are ignored by PHPUnit's test double functionality and retain their original behavior.
I just stumbled upon this issue today. Another alternative is to mock the interface that the class implements, given that it implements an interface and you use the interface as type hinting.
For example, given the problem in question, you can create an interface and use it as follows:
interface Interface_To_Mock
{
function needsToBeCalled($options);
}
class Class_To_Mock implements Interface_To_Mock
{
final public function needsToBeCalled($options)
{
...
}
}
class Class_To_Be_Tested
{
public function setClassToMock(Interface_To_Mock $classToMock)
{
...
}
...
}
class MyTest extends PHPUnit_Framework_TestCase
{
public function testDoSomething()
{
$mock = $this->getMock('Interface_To_Mock', array('needsToBeCalled'));
...
}
}
Related
I have function like this:
class Bar{
public function a():Foo{
.
.
.
}
}
now I am trying to create a mock for the class Bar with php unit test
$mockedBar = $this->getMockBuilder(Bar::class)
->getMock()
->method('a')
->willReturn(new FakeFoo());
but when I am calling method a I am getting an error that method a return type must be instance of Foo not Mocked_blahblah.
unfortunately class Bar don't use any interface and the system is very big and I can't create an interface cause it make huge refactor in my codes;
is there any way to disable return type of function a in mocked object?
I am useing php7.2 and phpunit 6.0.13.
Here is a real scenario:
class A
{
public function b():B
{
echo "i am from class A function b";
}
}
class B
{
}
class FakeB
{
}
class ATest extends TestCase
{
public function testSayHi(){
$mockedA = $this->getMockBuilder(A::class)
->getMock();
$mockedA->method('b')->willReturn(new FakeB());
$mockedA->b();
}
}
You can't disable return types. Perhaps you could try to do it with some kind of a hackish error handler, but it's a crazy thing to do.
Good news is that you're not trying to do anything unusual and your tests can be fixed.
Firstly, you need to assign the result of getMock to a variable. Next, you can define your test double:
class MyTest extends TestCase
{
public function testIt()
{
$mockedBar = $this->getMockBuilder(Bar::class)->getMock();
$mockedBar
->method('a')
->willReturn(new FakeFoo());
$this->assertInstanceOf(Foo::class, $mockedBar->a());
}
}
This will only work if FakeFoo is of type of Foo, for example extends it:
class FakeFoo extends Foo
{
// override any Foo methods you'd like to fake
}
You don't need to create a Fake yourself, you can use PHPUnit to create a dummy:
class MyTest extends TestCase
{
public function testIt()
{
$mockedBar = $this->createMock(Bar::class);
$mockedBar
->method('a')
->willReturn($this->createMock(Foo::class));
$this->assertInstanceOf(Foo::class, $mockedBar->a());
}
}
To fix your second example:
class A
{
public function b():B
{
echo "i am from class A function b";
}
}
class B
{
}
class FakeB extends B
{
}
class ATest extends TestCase
{
public function testSayHi(){
$mockedA = $this->getMockBuilder(A::class)->getMock();
$mockedA->method('b')->willReturn(new FakeB());
$mockedA->b();
}
}
Or, instead of using a fake let phpunit handle it:
class ATest extends TestCase
{
public function testSayHi(){
$mockedA = $this->getMockBuilder(A::class)->getMock();
$dummyB = $this->createMock(B::class);
$mockedA->method('b')->willReturn($dummyB);
$mockedA->b();
}
}
Have a look at the following trait:
trait PrimaryModelRest {
use RestController;
protected $primaryModel;
public function __construct() {
$mc = $this->getPrimaryModelClass();
try {
$this->primaryModel = new $mc();
if(!($this->primaryModel instanceof Model)) {
throw new ClassNotFoundException("Primary Model fatal exception: The given Class is not an instance of Illuminate\Database\Eloquent\Model");
}
} catch (Exception $e) {
throw new WrongImplementationException("Primary Model Exception: Class not found.");
}
}
/**
* #return string: Classname of the primary model.
*/
public abstract function getPrimaryModelClass();
// various functions here
}
As you can see the trait makes sure that the using class holds a certain model instance and it implements certain methods. This works as long as the implementing class does not override the constructor.
So here is my question: I want to make sure that either the constructor is called or a better solution, such that I can instantiate this model on initialization.
Please make in answer which respects Multiple inheritance as well es Multi-Level inheritance.
I think you are trying to make the trait do a job it is not designed for.
Traits are not a form of multiple inheritance, but rather "horizontal reuse" - they're often described as "compiler-assisted copy-and-paste". As such, the job of a trait is to provide some code, so that you don't have to copy it into the class manually. The only relationship it has is with the class where the use statement occurs, where the code is "pasted". To aid in this role, it can make some basic requirements of that target class, but after that, the trait takes no part in inheritance.
In your example, you are concerned that a sub-class might try to access $primaryModel without running the constructor code which initialises it, and you are trying to use the trait to enforce that; but this is not actually the trait's responsibility.
The following definitions of class Sub are completely equivalent:
trait Test {
public function foo() {
echo 'Hello, World!';
}
}
class ParentWithTrait {
use Test;
}
class Sub inherits ParentWithTrait {
}
vs:
class ParentWithMethodDefinition {
public function foo() {
echo 'Hello, World!';
}
}
class Sub inherits ParentWithMethodDefinition {
}
In either case, class Sub could have its own definition of foo(), and by-pass the logic you'd written in the parent class.
The only contract that can prevent that is the final keyword, which in your case would mean marking your constructor as final. You can then provide an extension point that can be overridden for sub-classes to add their own initialisation:
class Base {
final public function __construct() {
important_things(); // Always run this!
$this->onConstruct(); // Extension point
}
protected function onConstruct() {
// empty default definition
}
}
class Sub {
protected function onConstruct() {
stuff_for_sub(); // Runs after mandatory important_things()
}
}
A trait can also mark its constructor as final, but this is part of the code being pasted, not a requirement on the class using the trait. You could actually use a trait with a constructor, but then write a new constructor as well, and it would mask the trait's version completely:
trait Test {
final public function __construct() {
echo "Trait Constructor";
}
}
class Noisy {
use Test;
}
class Silent {
use Test;
public function __construct() {
// Nothing
}
}
As far as the trait is concerned, this is like buying a bottle of beer and pouring it down the sink: you asked for its code and didn't use it, but that's your problem.
Crucially, though, you can also alias the methods of the trait, creating a new method with the same code but a different name and/or a different visibility. This means you can mix in code from traits which declare constructors, and use that code in a more complex constructor, or somewhere else in the class altogether.
The target class might also use the "final + hook" pattern:
trait TestOne {
final public function __construct() {
echo "Trait TestOne Constructor\n";
}
}
trait TestTwo {
final public function __construct() {
echo "Trait TestTwo Constructor\n";
}
}
class Mixed {
final public function __construct() {
echo "Beginning\n";
$this->testOneConstructor();
echo "Middle\n";
$this->testTwoConstructor();
echo "After Traits\n";
$this->onConstruct();
echo "After Sub-Class Hook\n";
}
use TestOne { __construct as private testOneConstructor; }
use TestTwo { __construct as private testTwoConstructor; }
protected function onConstruct() {
echo "Default hook\n";
}
}
class ChildOfMixed extends Mixed {
protected function onConstruct() {
echo "Child hook\n";
}
}
The trait hasn't forced the Mixed class to implement this pattern, but it has enabled it, in keeping with its purpose of facilitating code reuse.
Interestingly, the below code doesn't work, because the as keyword adds an alias, rather than renaming the normal method, so this ends up trying to override the final constructor from Mixed:
class ChildOfMixed extends Mixed {
use TestTwo { __construct as private testTwoConstructor; }
protected function onConstruct() {
$this->testTwoConstructor();
echo "Child hook\n";
}
}
Use a base class, this will let you handle the trait as a parent.
<?php
trait StorageTrait
{
public function __construct()
{
echo "Storage Trait";
}
}
class StorageAttempt
{
use StorageTrait;
public function __construct()
{
parent::__construct();
echo " - Storage Attempt";
}
}
abstract class StorageBase
{
use StorageTrait;
}
class MyStorage extends StorageBase
{
public function __construct()
{
parent::__construct();
echo ' - My Storage';
}
}
new StorageAttempt(); // won't work - will trigger error
new MyStorage(); // will display "Storage Trait - My Storage"
Also if you are using traits you can also work with properties and getters & setters.
Example: A Storage trait involves that a Storage Engine will be used. You can add the storageEngine property and its getters and setters. (with or without Type Hinting)
interface StorageEngineInterface{}
trait StorageTrait
{
/**
* #var StorageEngineInterface
*/
protected $storageEngine;
/**
* #return StorageEngineInterface
*/
public function getStorageEngine(): StorageEngineInterface
{
return $this->storageEngine;
}
/**
* #param StorageEngineInterface $storageEngine
*/
public function setStorageEngine(StorageEngineInterface $storageEngine)
{
$this->storageEngine = $storageEngine;
return $this;
}
}
Note: this is just an explanation so you can better understand how Traits work
UPDATE
To avoid conflict you can use aliases for trait methods. This way you can use both constructors (from trait and from extended class) you can do the following
class DifferentStorage
{
public function __construct()
{
echo ' diff ';
}
}
class MyDifferentStorage extends DifferentStorage
{
use StorageTrait {
StorageTrait::__construct as otherConstructor;
}
public function __construct()
{
parent::__construct();
self::otherConstructor();
}
}
You could use the interface injection pattern: implement an interface iPrimaryModelRest into the same class that uses the trait PrimaryModelRest:
interface iPrimaryModelRest {
public function init();
public abstract function getPrimaryModelClass();
}
The class that uses the trait woud look like this:
class cMyClass implements iPrimaryModelRest {
use PrimaryModelRest;
}
Then, whenever the class is instantiated (not only autoloaded) you could call a special factory-like initialisation function like this:
class cMyApp {
public function start() {
/** #var cMyClass $oClass */ // enlighten IDE
$oClass = $this->init(new cMyClass);
}
public function init($oClass) {
if ($oClass instanceof iPrimaryModelRest) {$oClass->init();}
if ($oClass instanceof whateverinterface) {
// pass optional stuff, like database connection
}
}
}
The interface is used to determine the capabilities of the class, and sets data/runs corresponding functions. If I'm not mistaken then this pattern is called a Service Locator.
I needed a trait for database connection. To avoid using the __construct in a trait, I've used a magic getter instead:
trait WithDatabaseConnection
{
public function __get(string $name)
{
if ($name === 'pdo') {
return App::make(\PDO::class);
}
trigger_error("Property $name does not exist.");
return null;
}
}
class Foo {
use WithDatabaseConnection;
public function save() {
$this->pdo->query('...');
}
}
Im talking about this function:
function testMeSomehow ($id, Flag $flags)
{
$flags::NAME;
}
its parameter object:
abstract class Flag
{
abstract function method1();
abstract function method2();
.
.
.
abstract function method999();
}
how to mock this Flag class? It has tons of abstract methods, should I create all of them with empty body? And what if this class changes? I also have to add a NAME constant to it
You can mock it with test doubles like you would do for any other class, see https://phpunit.de/manual/current/en/test-doubles.html
This could be an example test:
class TargetClass
{
public function testMeSomehow($id, Flag $flag)
{
return $flag->method1();
}
}
class TargetClassTest extends PHPUnit_Framework_TestCase
{
public function testSomething()
{
$mock = $this->getMock('Flag');
$mock->expects($this->once())
->method('method1')
->willReturn('methodResult');
$targetClass = new TargetClass();
$this->assertEquals('methodResult', $classToTest->testMeSomehow(1, $mock));
}
}
You can specify the methods that you want to replace by the mock as the 2nd parameter of $this->getMock(). Because we don't specify anything at all, it will replace all methods and thus won't bother about the abstract methods.
Edit: added an example to access constants:
class ClassToTest
{
public function testMeSomehow($id, Flag $flag)
{
return $flag::NAME;
}
}
class FlagTest extends PHPUnit_Framework_TestCase
{
public function testStuff()
{
$mock = $this->getMock('Flag');
$classToTest = new ClassToTest();
$this->assertEquals('Flag name', $classToTest->testMeSomehow(1, $mock));
}
}
If you want a specific value for that constant in your tests, I suggest to make a child class with this constant and use that for mocking.
Edit: added an example with a workaround to specify dynamic constant values.
class Flag
{
const NAME = 'Flag name';
public function getName()
{
return static::NAME;
}
}
class TargetClass
{
public function testMeSomehow($id, Flag $flag)
{
return $flag->getName();
}
}
class TargetClassTest extends PHPUnit_Framework_TestCase
{
public function testSomething()
{
$mock = $this->getMock('Flag');
$mock->expects($this->any())
->method('getName')
->willReturn('New flag name');
$targetClass = new TargetClass();
$this->assertEquals('New flag name', $classToTest->testMeSomehow(1, $mock));
}
}
However, this compels you to use the getName() method everywhere, so I personally prefer the previous suggestion: mocking a child class that has the changed value.
I am trying to write a test for some very old code we have using PHPUnit. I've given the rough structure of it here, I am trying to test the isMember() method of ClassB which it inherits from ClassA. It should just be checking if a constant value exists in the class.
The problem I am having is that it is obviously a protected constructor, so I don't know how to test this as I keep getting protected contruct errors in PHPUnit as obviously the constructor is protected. Please advise how I test this?
abstract class ClassA implements InterfaceA {
private $mValueList;
protected static $instance;
protected function __construct() {
}
protected static function getInstance(ClassA $obj) {
if (is_null($obj->instance)) {
$obj->instance = $obj;
}
return $obj->instance;
}
public function isMember($value) {
return isset($this->mValueList[$value]);
}
....more methods......
}
class ClassB extends ClassA {
public static function getInstance() {
return parent::getInstance(new self());
}
const CON1 = 'string1';
const CON2 = 'string2';
}
You would test it like any other class, you just don't use the constructor in the test.
public function testIsMember() {
$classB = ClassB::getInstance();
$this->assertTrue($classB->isMember('string1'));
$this->assertFalse($classB->isMember('foo'));
}
I am making a guess on the assertions and you could refactor the test to use a data provider. But the general idea is the same. You don't invoke the constructor directly in your tests for a singleton. The getInstance method replaces the call to the constructor.
I have a state object that extends a base abstract class that implements SplSubject.
This state is then passed to the observers notify method however - my unit tests and IDE complain over type involved.
abstract class TQ_Type implements \SplObserver
{
public function update(TQ_State $tq_state)
{
...
}
}
abstract class TQ_State implements \SplSubject
{
public function __construct()
{
$this->observers = new SplObjectStorage;
}
public function attach(TQ_Type $observer)
{
$this->observers->attach($observer);
}
public function detach(TQ_Type $observer)
{
$this->observers->detach($observer);
}
public function notify()
{
foreach ($this->observers as $observer)
{
$observer->update($this);
}
}
}
The following test yields: PHP Fatal error: Declaration of TQ_State::attach() must be compatible with SplSubject::attach(SplObserver $SplObserver)
class TQTypeStandardAppealTest extends PHGUnit_Internal
{
private $under_test;
public function setUp()
{
$this->under_test = new TQ_Type_StandardAppeal();
}
public function test_pending_standard_appeal_tq_approval_hits_states_notify_method()
{
$state = Mockery::mock('TQ_State_Pending')->makePartial();
$state->shouldReceive('get_event')
->withNoArgs()
->andReturn('Approve');
$this->under_test->update($state);
}
}
I derive from these and those derived classes are the subject of the unit tests...
Is this an issue where mockery is not honouring the hierarchy of the object it is mocking
NB I have used a partial mock here as the actual mock returns a Mockery\CompositeExpectation but I'll deal with that later.
Derp on my behalf.
Plain and simple these must respect the contracts of the interface so they must have SplObserver and SplSubject. Any further requirement to restrict the ability of on object not of the correct type to trigger the update method of an observer must be handled within that method.