N
N
Nikita Kolosov2016-03-02 14:25:34
PHP
Nikita Kolosov, 2016-03-02 14:25:34

How to properly test interfaces using PHPUnit?

There is a certain library, it has a class:

class Foo
{
  public static function bar(MyInterface $example)
  {
    //some actions
    return 1;
  }
}

There is a test-case
class FooTest extends \PHPUnit_Framework_TestCase 
{
  public function testFoo()
  {
    //...create $object for testing
   self::assertEquals(1, Foo::bar($object));
  }
}

Accordingly, the question arises of how to properly test the method.
At first I tried to do $object = $this->getMock('MyInterface'), but the result is an object of type Mock_MyInterface, and when the method is called, the interpreter swears at type mismatches.
How to do it right? Implement a class that implements this interface in a folder with tests? Or is there another way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dbelka, 2016-03-10
@Anexroid

Strange, it should work
. This is how a class is created with an empty implementation of the interface, i.e. There can be no type mismatch. The only problem that may arise is methods that by default do not return anything, for example, you have a chain of calls like this in your code:

$obj->setId(1)
    ->setName("name");

in this case, you need to separately describe the stub for the methods:
Maybe you have some old PHPUnit, I have version 5.2.4

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question