I a unit-testing beginner and seem to be stuck on how to unit test a function that contains an internal function call. For example, testing the following:
public function getBlueFooCount($fooId) {
$foo = $fooDao->getFoosById($fooId);
// custom logic to pull out the blue foos from result set
// custom count business logic on blue foos ...
return $count;
}
How would I be able to mock what the internal function retrieves? Is this because the function is too tightly coupled and it needs to be loosened?
To build off #aib's answer, when we started to unit test our legacy code base the majority of our classes were very tightly coupled and many methods were instantiating new objects themselves. While we've taken steps on implementing Dependency Injection and Inversion of Control going forward, we were still stuck with hundreds of classes that still needed unit tested.
When writing a unit test for a legacy method, we refactored and pulled the instantiation out into a new small method we could then stub. Not the best pattern, but it was cheap and got the job done without having to do a larger refactoring.
class FooCounter {
public function getFooDao(){
return new FooDao();
}
public function getBlueFooCount($fooId) {
/* was this
$fooDao = new FooDao();
*/
$foo = $this->getFooDao()->getFoosById($fooId);
// custom logic to pull out the blue foos from result set
// custom count business logic on blue foos ...
return $count;
}
}
class FooCounterTest extends PHPUnit_Framework_TestCase {
public function test_getBlueFooCount(){
$fooCounter = $this->getMock('FooCounter', array('getFooDao'));
$fooCounter->expects($this->any())
->method('getFooDao')
->will($this->returnValue(new MockFooDao()));
$this->assertEquals(0, $fooCounter->getBlueFooCount(1));
}
}
If we were implementing a new class, we typically are using constructor based DI and it is the answer I will give if you are creating something new. Here's a link by someone else because I trust it's been said better before (sort of DRY): Dependency Injection and Unit Testing. And some examples of each for your case:
Constructor based injection
class FooCounter {
private $_fooDao
public function __construct($fooDao){
$this->_fooDao = $fooDao
}
public function getBlueFooCount($fooId) {
$foo = $this->_fooDao->getFoosById($fooId);
// custom logic to pull out the blue foos from result set
// custom count business logic on blue foos ...
return $count;
}
}
class FooCounterTest extends PHPUnit_Framework_TestCase {
public function test_getBlueFooCount(){
$fooCounter = new FooCounter(new MockFooDao());
$this->assertEquals(0, $fooCounter->getBlueFooCount(1));
}
}
Setter based injection
class FooCounter {
private $_fooDao
public function setFooDao($fooDao){
$this->_fooDao = $fooDao
}
public function getBlueFooCount($fooId) {
$foo = $this->_fooDao->getFoosById($fooId);
// custom logic to pull out the blue foos from result set
// custom count business logic on blue foos ...
return $count;
}
}
class FooCounterTest extends PHPUnit_Framework_TestCase {
public function test_getBlueFooCount(){
$fooCounter = new FooCounter();
$fooCounter->setFooDao(new MockFooDao());
$this->assertEquals(0, $fooCounter->getBlueFooCount(1));
}
}
You need to mock $fooDao. Hopefully there's a setter or a DI container and you're not creating it with new (in which case it might be too tightly coupled.)
Related
Is injection of the same class a good practice?
I am using self-injection for years to isolate methods during PHPunit testing:
class Meter extends Model
{
use SomeTrait;
protected self $self;
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->self = $this;
}
public function setSelfDI(self $self): self
{
$this->self = $self;
return $this;
}
public function calculate(): int
{
return $this->self->getDiametr() * 3.1415926;
}
public function getDiametr(): int
{
return parent::getRadius() * 2;
}
}
to test calculate() method I can't just call it since it calls method getDiametr() which depends on other trait or class.
And I believe it is bad practice to test mocked class.
So I inject mocked class in my class and so isolate method during testing:
public function testCalculate(): void
{
/** #var Meter|MockObject $mock */
$mock = $this->createMock(Meter::class);
$mock->expects($this->once())
->method('getDiametr')
->willReturn(100);
$meter = new Meter();
$meter->setSelfDI($mock);
static::assertEquals(314.15926, $meter->calculate());
}
It works perfectly for me.
But recently I got a code review that it is not a valid pattern to introduce synthetic functionality setSelfDI() on top of functional code just to be able to test it.
Now I have a normal DI pattern that I love to use vs setSelfDI() setter that is never used but for tests.
How to decide it is good or bad practice?
I believe it is bad practice to test mocked class.
If you really believe that, you have answered your own question, because that's exactly what you're doing - you're mocking some methods of the class and testing others.
It's important not to just read a bulleted list of "best practices" but to understand why each of those rules is proposed. In this case, the idea is that you should have a particular "unit" of code that you are testing; functionality that is the responsibility of that "unit" should be tested, and functionality that it relies on should be decoupled and tested separately.
That's not just a recommendation about testing, it's a recommendation about architecting your code - the Single Responsibility Principle.
In your example, the better design might be one of several things:
If the radius is just data, you don't need to mock it, create a real instance with a known radius
If calculating the radius is the responsibility of some other component with its own tests, pass in that object as a dependency rather than inheriting from it (commonly summarised, "prefer composition over inheritance")
If calculating the data is not an input or independent calculation in the real code, don't treat it as one in the test: you should be testing the contract of the class - its inputs, outputs, and side effects - not how it is implemented
If radius is an input to the class being tested, the test would be simple:
public function testCalculate(): void
{
$meter = new Meter(['radius' => 50);
static::assertEquals(314.15926, $meter->calculate());
}
Using composition rather than inheritance, you might have a test like this:
public function testCalculate(): void
{
// Mock the collaborating class, not the one being tested
$mock = $this->createMock(Model::class);
// Note that we're mocking getRadius, not getDiametr
// getDiametr is part of the implementation we're testing
$mock->method('getRadius')
->willReturn(50);
// Meter doesn't inherit from Model
// Instead, it requires an instance to be injected
$meter = new Meter($mock);
static::assertEquals(314.15926, $meter->calculate());
}
Note that in both cases the parts that we're hard-coding in the test are the radius of 50 and the result of 314.15926, not the diameter of 100 - the contract that we're testing is "given a radius of 50, the result should be 314.15926". The fact that calculate() shares code with getDiametr() is the implementation by which you've fulfilled that contract.
The following implementations should all pass the same tests. The point of the tests is to guarantee that after you've changed the implementation, the contract hasn't been violated - in other words, the code will still do what the rest of your application expects it to do.
// Fully shared
class Meter {
// ...
public function calculate(): int
{
return $this->getDiameter() * 3.1415926;
}
public function getDiameter(): int
{
return $this->getRadius() * 2;
}
}
// Fully copy-and-pasted
class Meter {
// ...
public function calculate(): int
{
return $this->getRadius() * 2 * 3.1415926;
}
public function getDiameter(): int
{
return $this->getRadius() * 2;
}
}
// Partially shared
class Meter {
// ...
private function getDiameterInternal(): int
{
return $this->getRadius() * 2;
}
public function calculate(): int
{
return $this->getDiameterInternal() * 3.1415926;
}
public function getDiameter(): int
{
return $this->getDiameterInternal();
}
}
// Delegated to a dependency, but still meeting the original contract
class Meter {
// ...
private $someOtherObject;
public function calculate(): int
{
return $this->someOtherObject->getDiameter() * 3.1415926;
}
public function getDiameter(): int
{
return $this->someOtherObject->getDiameter();
}
}
Any of the above methods could also be in a Trait, which represents neither inheritance nor composition, but "horizontal code reuse", or more plainly "compiler-assisted copy-and-paste".
In an application I'm building there's a CLI entry point class:
class CLIEntryPoint {
protected $factory;
public function __construct(ApplicationObjectFactoryInterface $factory) {
$this->factory = $factory;
}
public function run(...$args) {
$choice = $args[1];
$appObject = $this->factory->makeApplicationObject($choice);
$appObject->doApplicationRelatedStuff();
}
}
This entry point is created using Dependency Injection in my "front controller" script and it receives an ApplicationObjectFactoryInterface implementation (actually the current implementation of ApplicationObjectFactoryInterface is injected by the DI container, which in turn reads it from its configuration file, but that's not the point).
The current implementation of ApplicationObjectFactoryInterface also uses DI and depends on other factories which help it building the resulting application object:
class CurrentImplementationOfApplicationObjectFactory implements ApplicationObjectFactoryInterface {
protected $someComponentFactory;
protected $anotherComponentFactory;
public function __construct(SomeComponentFactoryInterface $someComponentFactory, AnotherComponentFactoryInterface $anotherComponentFactory) {
$this->someComponentFactory = $someComponentFactory;
$this->anotherComponentFactory = $anotherComponentFactory;
}
/**
* Interface's method
*
* #return ApplicationObjectInterface
*/
public function makeApplicationObject($choice) {
$component = $this->someComponentFactory->makeSomeComponent();
$anotherComponent = $this->anotherComponent->makeAnotherComponent();
switch ($choice) {
case 1:
return new CurrentImplementationOfApplicationObject1($component, $anotherComponent);
case 2:
return new CurrentImplementationOfApplicationObject2($component, $anotherComponent);
default:
return new DefaultImplementationOfApplicationObject($component, $anotherComponent);
}
}
}
Here CurrentImplementationOfApplicationObject1, CurrentImplementationOfApplicationObject2 and DefaultImplementationOfApplicationObject all implement the ApplicationObjectInterface interface and therefore they all have the doApplicationRelatedStuff method.
I would like to know whether it's good practice or not to write code like I did and if not how can I improve it.
Basically here I am creating a component which depends on other components in order to function properly using a factory which in turn needs inner factories to build the component which implements the ApplicationObjectInterface interface.
Is it considered good practice?
Thanks for the attention, as always!
EDIT: I looked at the article of Steven and tried to refactor CLIEntryPoint. The only problem now seems to be how to pass the $choice parameter to the factory which now is inside of the proxy when the run() method is called. Is this code structure better than the one I posted above? Of course, SomeComponentFactoryInterface and AnotherComponentFactoryInterface should follow the same behaviour (the factory that uses them should not use them directly, but through two proxies which implement, in order, SomeComponentInterface and AnotherComponentInterface). I hope I get it right, anyway, here is the code:
class CLIEntryPoint {
protected $applicationObject;
public function __construct(ApplicationObjectInterface $applicationObject) {
$this->applicationObject = $applicationObject;
}
public function run(...$args) {
$choice = $args[1]; // How do I deal with different choices when I am using a Proxy? I should have different application objects depending on input.
$this->applicationObject->doApplicationRelatedStuff();
}
}
interface ApplicationObjectInterface {
public function doApplicationRelatedStuff();
}
class ApplicationObjectProxy implements ApplicationObjectInterface {
protected $applicationObjectFactory;
protected $applicationObjectImplementation = NULL;
public function __construct(ApplicationObjectFactoryInterface $factory) {
$this->applicationObjectFactory = $factory;
}
public function __call($method, $args) {
// Calling interface's
$implementation = $this->getImplementation();
$methodOfInterfaceToCall = preg_replace('/Proxy$/', '', $method);
return $implementation->{$methodOfInterfaceToCall}(...$args);
}
/**
* Laxy loading method.
*/
protected function getImplementation() {
if (is_null($this->applicationObjectImplementation)) {
$this->applicationObjectImplementation = $this->applicationObjectFactory->makeApplicationObject(); // Choice should go here somehow...
}
return $this->applicationObjectImplementation;
}
public function doApplicationRelatedStuff() {
// This will call the PHP's magic `__call` method, which in turn will forward the call to the application object's
// implementation returned by the factory.
return $this->doApplicationRelatedStuffProxy();
}
}
Actually yes, this is a pattern called the Abstract Factory Pattern. So an example that I used to present it in front of my class during my undergrad:
So if you are building a video game first person shooter, you might want to create three concrete factories like:
FlyingMonsterFactory
SwimmingMonsterFactory
WalkingMonsterFactory.
All these factories would implement an abstract MonsterFactory.
With this, you can have your video game create a level in which you want waves of the same type of monsters, so you can have a randomWaveMonsterGenerator method return a MonsterFactory which might have returned a concrete SwimmingMonsterFactory. So then you will have a wave of SwimmingMonster(s) generated by the SwimmingMonsterFactory.
So answer your description more directly, looking at your code above, you asked the question on choice for Dependency Injection. With Dependency Injection, I believe for this type of pattern, you will have to inject every concrete class before your code even attempts to get the implementation class.
So for example:
Your code above says the run method gives an argument called
choice.
With this choice, you will have to use it as a parameter into a getImplementation method.
All the concrete objects that the getImplementation method that rely upon Dependency
Injection have to be created BEFORE you call the getImplementation method.
But since you don't know which implementation class will be called, I believe you have to inject ALL the implementation classes before hand.
Then you can use the choice variable as a parameter to get the correct implemented factory class.
Hope this helps!
So I have read that if we see a switch statement, its a sign that it needs polymorphism.
I saw such polymorphism example:
include 'vendor/autoload.php';
$calc = new Calculator();
$calc->setOperands(5, 6);
$calc->setOperation(new Addition);
echo $result = $calc->calculate();
And of course there can be various classes as Subtract, Multiply, Root, etc.
Now lets say I want to use this code in a Laravel framework, but this I think should apply to any php framework.
Example of addition class ( same way could work any other calculator function)
Class Addition implements Operation {
public function run($num, $current){
return $current + $num;
}
}
Calculator:
Class Calculator {
protected $result = 0;
protected $operands = array();
protected $operation;
public function getResult()
{
return $this->result;
}
public function setOperands()
{
$this->operands = func_get_args();
}
public function setOperation(Operation $operation)
{
$this->operation = $operation;
}
public function calculate()
{
foreach ($this->operands as $num) {
echo $num;
if ( ! is_numeric($num)) {
throw new InvalidArgumentException;
}
$this->result = $this->operation->run($num, $this->result);
}
return $this->result;
}
}
I write a class like this:
class CalcUser
{
private $calc;
public function __construct(Calculator $calc)
{
$this->calc = $calc;
}
public function index()
{
$this->calc->setOperands(5, 6);
$this->calc->setOperation(new Addition);
$result = $calc->calculate();
// imagine we have long formula to calculate so we add here many functions
// (5+6) * 12 + 21 / 6 + sqrt(4) ...
$this->calc->setOperands($result, 6);
$this->calc->setOperation(new AnyOtherFunction);
echo $result = $calc->calculate();
}
}
And this should work, did not test my CalcUser class, just wrote directly here.
But I see one problem - there is used keyword new
And also what I have read is this:
Signs of Untestable Code:
New Operators
The only time when it’s acceptable to instantiate a class inside of
another class is when that object is what we refer to as a
value-object, or a simple container with getters and setters that
doesn’t do any real work.
Ok, now I could add the Addition class, and other classes to constructor as parameter like I did with calculator class and new operator will be avoided.
But then there is another thing:
Too Many Dependencies
If you find that a particular class requires four or more
dependencies, this is, more often than not, a tell-tale sign that your
class is asking for too much
And so its easily to get more than 3 dependencies that way with calculator alone having many different functions.
So how should I reformat code to avoid having too many dependencies?
There are a bunch of different views on this matter (when does a class depend on something), but class dependencies are typically seen as what's passed into the constructor, i.e. what's needed for the class to be instantiated as an object. Therefore, when you have an instance of your calculator, calling a method and passing another object - in this case an implementation of Operation - into a method is not a direct dependency.
So basically your Calculator class has no dependencies, your CalcUser has one dependency (Calculator).
Also, I think the thing about the new-keyword/construct is that a class should not call something on itself, passing a method dependency through there. That could be a sign that the newly instantiated object is redundant if it's only used in that class' ecosystem. Say you never use Operation anywhere else beside in the class that depends on it, i.e. in this case:
class Calculator
{
...
public function newSumOperation()
{
$this->setOperands(func_get_args());
$this->setOperation(new Addition);
}
...
}
class CalcUser
{
...
public function index()
{
$this->calc->newSumOperation(1,2,3);
$result = $this->calc->calculate();
// imagine we have long formula to calculate so we add here many functions
// (5+6) * 12 + 21 / 6 + sqrt(4) ...
$this->newXXXXXOperation(4,3,2);
echo $result = $calc->calculate();
}
}
So, as you see, in the above example you never use Addition outside the Calculator-class. If you think of a real calculator, you put numbers in and get the result out; and in between that, the calculator doesn't push the logic of adding numbers together over to something else, because it's the calculators job to do an addition.
I want to know if this tutorial is correctly implementing factory design pattern in PHP. Below is the actual source code.
<?php
class Automobile
{
private $vehicle_make;
private $vehicle_model;
public function __construct($make, $model)
{
$this->vehicle_make = $make;
$this->vehicle_model = $model;
}
public function get_make_and_model()
{
return $this->vehicle_make . ' ' . $this->vehicle_model;
}
}
class AutomobileFactory
{
public static function create($make, $model)
{
return new Automobile($make, $model);
}
}
// have the factory create the Automobile object
$veyron = AutomobileFactory::create('Bugatti', 'Veyron');
print_r($veyron->get_make_and_model()); // outputs "Bugatti Veyron"
According to a book "Design Patterns" by Gang of Four, applicability of factory pattern is
a class can't anticipate the class of objects it must create
a class wants its subclasses to specify the objects it creates
classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate
First point, this example actually knows what class of objects to create, which is Automobile, doesn't it?
Second point, there is no subclass. Automobile class does not inherit from AutomobileFactory. I thought AutomobileFactory should have at least one function implemented by Automobile, which deals with object creations.
Can someone clarify this? I just started learning design patterns, and every time I encounter tutorials different from others, it confuses me a lot.
I pretty much agree with what is said in Wikipedia
The creation of an object precludes its reuse without significant duplication of code.
The creation of an object requires access to information or resources that should not be contained within the composing class.
The lifetime management of the generated objects must be centralized to ensure a consistent behavior within the application.
The main reason I create factories is this one I highlighted.
For example, let's imagine a real world factory with many plants throughout the country. This factory produces doors. Doors needs knobs. For logistics reasons, each one of the plants of the factory has its own knob suppliers, another completely different factory.
The production manager software of this factory will choose based on some criteria which plant will produce a lot of doors, but it does not need to know from where the knobs will come. The chosen plant will ask for its own supplier for a knob for the produced door.
However, for the client, it does not matter which plant made the door, he only cares about having his door.
Let's put this on code:
class Knob {
// something...
}
interface KnobSupplier {
public function makeKnob();
}
class SaoPauloKnobSupplier {
public function makeKnob() {
return new Knob('Knob made in São Paulo');
}
}
class NewYorkKnobSupplier {
public function makeKnob() {
return new Knob('Knob made in New York');
}
}
class Door {
public function __construct(Knob $knob) {
// something...
}
}
interface DoorFactory {
public function makeDoor();
}
class SaoPauloDoorFactory {
private $knobSupplier;
public function __construct() {
$this->knobSupplier = new SaoPauloKnobSupplier();
}
public function makeDoor() {
return new Door($this->knobSupplier->makeKnob(), "Door made in São Paulo");
}
}
class NewYorkDoorFactory {
private $knobSupplier;
public function __construct() {
$this->knobSupplier = new NewYorkKnobSupplier();
}
public function makeDoor() {
return new Door($this->knobSupplier->makeKnob(), "Door made in New York");
}
}
class ProductionManager {
private $plants = array();
// methods for adding plants, etc...
public function getDoor() {
// Somehow decides which plant will create the door.
return $plant->makeDoor();
}
}
class Client {
public function getMyDoor(ProductionManager $manager) {
return $manager->getDoor();
}
}
Using this code like:
$manager = new ProductManager();
$manager->addPlant(new SaoPauloDoorFactory());
$manager->addPlant(new NewYorkDoorFactory());
$client = new Client();
var_dump($client->getMyDoor($manager));
ProductManager does not know anything about knobs, Client does not know anything about the factory having more than one plant.
I don't really like the tutorial. As you can see in the WikiPedia page about factories ( https://en.wikipedia.org/wiki/Factory_pattern ) - it's normally done differently. The WikiPedia example does comply with the rules you mention. Check out the PHP section there.
I'm with you kidonchu, I don't really see that example as a traditional factory method pattern.
I would write your example like this (psuedo code)
<?php
abstract class CarAbstract
{
protected $_vehicleMake;
protected $_vehicleModel;
public function __construct($model)
{
$this->_vehicleModel = $model;
}
public function getMakeAndModel()
{
return $this->_vehicleMake . ' ' . $this->_vehicleModel;
}
}
class Bugatti extends CarAbstract
{
public function __construct($model)
{
parent::__construct($model);
$this->_vehicleMake = get_class($this);
}
}
class AutomobileFactory
{
public static function getInstance($make, $model)
{
if (is_file('Model/Car/' . $make . '.php')){
require_once 'Model/Car/' . $make . '.php';
$car = new $make($model);
}else{
throw new Exception('Car not found');
}
}
}
$veyron = AutomobileFactory::getInstance('Bugatti', 'Veyron');
print_r($veyron->getMakeAndModel()); // outputs "Bugatti Veyron"
There's actually a single Factory Method design pattern following the original gang of four catalog. The Abstract Factory is wholly different and is based on different structural assumptions. The Simple Factory is not a design pattern, but the what Freemans call a 'programming idiom.' The Factory method includes an abstract Creator and Product, and the Clients generally make their requests through the Creator. Specific factories are found in the ConcreteCreator(s) and the concrete products are child classes of the Product class and are instantiated by concrete creators. For a complete and simple PHP example see http://www.php5dp.com/a-simple-php-design-pattern-the-factory-method/.
I'm used to the habit of writing like this:
$results = SomeModelQuery::create()->filterByFoo('bar')->find();
However this does not scale for unit testing because I can't inject a mock object, i.e. I can't affect what data is returned. I'd like to use fixture data, but I can't.
Nor does it seem great to inject an object:
class Foo
{
public __construct($someModelQuery)
{
$this->someModelQuery = $someMOdelQuery;
}
public function doSthing()
{
$results = $this->someModelQuery->filterByFoo('bar')->find();
}
}
DI feels horrible. I have tens of query objects to mock and throw. Setting through constructor is ugly and painful. Setting using method is wrong because it can be forgotten when calling. And it feels painful to always for every single lib and action to create these query objects manually.
How would I elegantly do DI with PropelORM query classes? I don't want to call a method like:
$oneQuery = OneQuery::create();
$anotherQuery = AnotherQuery::create();
// ... 10 more ...
$foo = new Foo($oneQuery, $anotherQuery, ...);
$foo->callSomeFunctionThatNeedsThose();
In my opinion (and Martin Folowers's) there is a step between calling everything statically and using Dependency Injection and it may be what you are looking for.
Where I can't do full DI (Zend Framework MVC for example) I will use a Service Locator. A Service Layer will be the place that all your classes go to get there dependencies from. Think of it as a one layer deep abstraction for your classes dependencies. There are many benefits to using a Service Locator but I will focus on testability in this case.
Let's get into some code, here is are model query class
class SomeModelQuery
{
public function __call($method, $params)
{
if ($method == 'find') {
return 'Real Data';
}
return $this;
}
}
All it does is return itself unless the method 'find' is called. Then is will return the hard-coded string "Real Data".
Now our service locator:
class ServiceLocator
{
protected static $instance;
protected $someModelQuery;
public static function resetInstance()
{
static::$instance = null;
}
public static function instance()
{
if (self::$instance === null) {
static::$instance = new static();
}
return static::$instance;
}
public function getSomeModelQuery()
{
if ($this->someModelQuery === null) {
$this->someModelQuery = new SomeModelQuery();
}
return $this->someModelQuery;
}
public function setSomeModelQuery($someModelQuery)
{
$this->someModelQuery = $someModelQuery;
}
}
This does two things. Provides a global scope method instance so you can always get at it. Along with allowing it to be reset. Then providing get and set methods for the model query object. With lazy loading if it has not already been set.
Now the code that does the real work:
class Foo
{
public function doSomething()
{
return ServiceLocator::instance()
->getSomeModelQuery()->filterByFoo('bar')->find();
}
}
Foo calls the service locator, it then gets an instance of the query object from it and does the call it needs to on that query object.
So now we need to write some unit tests for all of this. Here it is:
class FooTest extends PHPUnit_Framework_TestCase
{
protected function setUp()
{
ServiceLocator::resetInstance();
}
public function testNoMocking()
{
$foo = new Foo();
$this->assertEquals('Real Data', $foo->doSomething());
}
public function testWithMock()
{
// Create our mock with a random value
$rand = mt_rand();
$mock = $this->getMock('SomeModelQuery');
$mock->expects($this->any())
->method('__call')
->will($this->onConsecutiveCalls($mock, $rand));
// Place the mock in the service locator
ServiceLocator::instance()->setSomeModelQuery($mock);
// Do we get our random value back?
$foo = new Foo();
$this->assertEquals($rand, $foo->doSomething());
}
}
I've given an example where the real query code is called and where the query code is mocked.
So this gives you the ability to inject mocks with out needing to inject every dependency into the classes you want to unit test.
There are many ways to write the above code. Use it as a proof of concept and adapt it to your need.