Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock frameworks returns class with different name and type

I'm trying to create a mock to satisfy a typehint with this code (Mockery):

return \Mockery::mock('\Contracts\Helpers\iFileSystemWrapper');

or this (PHPUnit):

return $this->getMock('\Contracts\Helpers\iFileSystemWrapper');

But the mock returned is called Mockery\Mock Object or Mock_iFileSystemWrapper_a5f91049. How am I supposed to type check this when it isn't an instance of what I need at all with either framework?

Why exactly is the mock framework trying to load the real class? If I wanted the real class I would include the real class.

This problem has slowed me down so many times when writing tests I'm about to just toss type hinting out the window and check class names instead, or simply use production objects as mocks are a pain to use.

like image 877
Seralize Avatar asked Jul 26 '12 21:07

Seralize


People also ask

How to mock model class using Mockito?

The Mockito. mock() method allows us to create a mock object of a class or an interface. We can then use the mock to stub return values for its methods and verify if they were called. We don't need to do anything else to this method before we can use it.

How to mock object class in JUnit?

We can use Mockito class mock() method to create a mock object of a given class or interface. This is the simplest way to mock an object. We are using JUnit 5 to write test cases in conjunction with Mockito to mock objects.

How can specify the mock behavior of an object?

When you create a mock, you create an associated behavior object that controls mock behavior. Use this object to define mock method and property behavior (stub). For more information on creating a mock, see Create Mock Object.


1 Answers

I just experimented with an existing test of my own, and by changing the interface namespace name from one that exists to one that doesn't exist, I got exactly the same as what you describe (using phpunit). My mock object had the class name Mock_ViewInterface_c755461e. When I change it back to the correct interface name, it works fine.

Therefore I would say that either:

  1. You are trying to use an interface name that doesn't exist (e.g. a typo or missing namespace component).
  2. Your library code isn't being loaded for some reason, e.g. autoloading is not setup correctly in your unit test bootstrap.
like image 172
leftclickben Avatar answered Oct 03 '22 22:10

leftclickben