I have a class that looks something like this:
class Foo {
protected $_arr = array();
public function has($key) {
return array_key_exists($key, $this->_arr);
}
public function add($key, $val) {
$this->_arr[$key] = $val;
}
}
For my PHPUnit tests for these methods, the only way I can think if to test add() is by asserting that has() returns TRUE for the same key after adding it. This makes my testAdd() test dependent on my testHas() test. Conversely, the only way I can think of to test has() is basically doing the exact same steps, but this would make this test dependent on an already dependent test, producing a chicken and egg type problem.
Am I going about this the wrong way? What's a better method for testing stuff like this?
Instead of writing one-test-per-method, design your tests around the functionality the class must provide. You'll have tests that exercise multiple methods, but that's fine because it indicates to the developer that those methods are related. This is where Test Driven Development--where you write the tests while designing the contract for the class before writing the code for the class--really shines.
class FooTest extends PHPUnit_Framework_TestCase
{
function testStartsEmpty() {
$foo = new Foo;
self::assertFalse($foo->has('bar'));
}
function testAddStoresKeys() {
$foo = new Foo;
$foo->add('bar', 'baz');
self::assertTrue($foo->has('bar'));
}
function testAddStoresKeysWithNullValues() {
$foo = new Foo;
$foo->add('bar', null);
self::assertTrue($foo->has('bar'));
}
function testAddStoresValues() {
$foo = new Foo;
$foo->add('bar', 'baz');
self::assertEquals('baz', $foo->get('bar')); // fatal error
}
}
Now that testAddStoresValues() fails, it's time to implement a method to get the value for a given key: Foo::get($key).
PHPUnit allows testing of non-public members.
However, using $sut->has() to find out whether $sut->add() worked is perfectly fine. Also, when you test $sut->add(), you dont need to write a separate test for $sut->has() as well, because it's covered in the $sut->add() test already. Just add a #covers annotation.
In reference to the long dicussions in the comments to #Gordon s answer:
The unit in unit testing is the object not the method! You don't want to test methods in isolation from the other methods of the objects. (If you wanted to do so just use functions ;) ) - It's really important to test how the object behaves and if it does the expected think when called and not how the methods interact internally.
I've recently written a blog post explaining why it is important to not test single methods in isolation:
http://edorian.posterous.com/the-unit-in-unit-testing
Quoting from my post:
Unit testing, in PHP, is about testing the observable behaviors of a class
Most importantly:
Observable from the outside! Nobody cares about the internal state of a class if it never changes the outcome of a method call.
Take this sample:
public function setValue($value) {
$this->value = $value;
}
public function execute() {
if (!$this->value) {
throw new Exception("No Value, no good");
}
return $value * 10; // business logic
}
It sounds trivial but the distinction is important and more easy to overlook when looking at bigger classes.
What do we test there?
IF we don’t setValue AND then call execute an exception is thrown!
IF we DO setValue AND then call execute we get an computed result
So we are testing two behaviors of your class and not the methods in isolation!
IMO you can test behavior of the object. So you can test if has return false before and true after adding some stuff into collection.
Related
I have been reading the PHPUnit docs online and have been using the mock object matchers but I am not sure when you should or shouldn't use them. For the example below, let's say I have a class Foo I am writing a test for:
Foo class
<?php
class Foo {
public function isUserNamedTom(User $user):bool
{
return strtoupper($user->getName()) === 'TOM';
}
}
My Test
<?php
use PHPUnit\Framework\TestCase;
class FooTest extends TestCase {
public function testIsUserNamedTom():void
{
$userMock = $this->getMockBuilder(User:class)
->disableOriginalConstructor()
->getMock();
$userMock->expects($this->once())
->method('getName')
->willReturn('tom');
$fooService = new Foo();
$response = $fooService->isUserNamedTom($userMock);
$this->assertTrue($response);
}
}
My question is should I be using $this->once() or not in this example and if I am not then what are the reasons.
Your tests should test the output of the method under test with as little knowledge as possible about the implementation of the method under test. You want the test to fail when the method no longer does what it's supposed to do, but you don't want it to fail when the method does the right thing in a different way.
In this case it seems irrelevant for the test of isUserNamedTom(User $user) whether user->getName() is called once, twice or never. The only important thing is that isUserNamedTom(User $user) returns true if and only if $user is named "tom", "Tom", "tOm", etc.
Therefore: No, I wouldn't check for $this->once() here.
I would even try to get by without mocking and pass an instantiated user object instead. But whether this is possible depends on your User class.
public function testIsUserNamedTom():void
{
$user = (new User())->setName('tom');
$this->assertTrue($fooService->isUserNamedTom($user));
}
Basically, when writing tests, it's always good to ask yourself under what circumstances you want them to fail. In your example, my guess is that your test shouldn't fail if someone refactored isUserNamedTom(User $user) so that the method no longer calls $user->getName() (but maybe uses a public property $user->name).
I'm developing unit tests on a project and I came across a class that does not contain constructor.
You may ask yourself, "How does this object exist then?"
Well, in another system, this object is generated and saved in database, so in the system where unit tests are required, there is no constructor defined for that class. But there is a need to test their functions so that if they are modified in the system in the future, the tests will indicate in which situations they are used, this will ensure me not to neglect the other points of the project that use it.
Within this environment, how can you test this type of class?
I tried using mocks, but mock brings all null attributes. In addition, a mocked object only comes as a result of a function that you say previously it will bring. So to test the functions of the object itself, this is not functional.
Any idea?
PS: Sorry for the bad english.
Constructors are optional. A class does not need a constructor for you to be able to instantiate it or test whether its methods are functioning correctly.
As I understand it, you want to test a method which behaves differently depending on a particular property, which would normally be set by a constructor but in your class isn't. That means that in the actual code usage, that property is probably being set directly at some point or there's a different method that sets its value.
In general, for testing these kinds of methods you should always set such a property yourself anyway. The reason for this is simple: a single test should only test one particular method. If you rely on the constructor, your test would be testing the combination of both the constructor and that method. Your test of the method will become dependent on the constructor behaving properly.
Imagine the following:
class Mood {
public $happy;
function __construct() {
$this->happy = true;
}
public function greet() {
if ($this->happy) {
return 'Hi!';
} else {
return 'Go away';
}
}
}
Let's say you want to test the behavior of the greet() method:
class MoodTest extends \PHPUnit\Framework\TestCase {
public function testGreet() {
$mood = new Mood();
$this->assertEqual('Hi!', $mood->greet())
}
}
This test would pass, because we assume the constructor is doing its job and is setting the $happy property to true. But there are two problems here:
We are not testing that the method works properly if $happy is false
We rely on the constructor to set $happy's initial value to true
This means things can change outside our control that would break this specific test, even though the function still works as expected. Business logic may change so that the constructor will set $happy to false initially. Or the developer's logic may change where the constructor disappears entirely and $happy is set in some other way (maybe a setHappy() method is introduced at some point).
To properly test the greet() method, there should be a test for every possible outcome. In this case the method has a single if statement, so there ought to be a test case for both outcomes of that condition:
class MoodTest extends \PHPUnit\Framework\TestCase {
public function testGreetIfHappy() {
$mood = new Mood();
$mood->happy = true;
$this->assertEqual('Hi!', $mood->greet())
}
public function testGreetIfNotHappy() {
$mood = new Mood();
$mood->happy = false;
$this->assertEqual('Go away', $mood->greet())
}
}
Now, no matter what happens to the constructor or business logic, these tests are testing only the behavior of the greet() method. Whatever else the constructor is doing (even if doesn't exist or does nothing at all) no longer has any effect on the tests of the greet() method.
Given I have a FruitSalad class (the system under test):
class FruitSalad
{
protected $fruits = [];
public function addFruit(Fruit $fruit)
{
$this->fruits[] = $fruit;
return $this;
}
}
And I have a Fruit class:
class Fruit
{
public static function withName($name)
{
$instance = new MyDependencyClass();
$instance->name = $name;
return $instance;
}
}
A trivial example, however you can see that the Fruit class uses a named static constructor, and the addFruit() method on the FruitSalad class type hints Fruit as its expected parameter.
When writing a test for addFruit(), I need to mock the Fruit class.
function test_it_can_add_a_fruit_to_its_list_of_fruits()
{
$fruit = $this->getMockBuilder('Fruit')
->disableOriginalConstructor()
->getMock();
$this->fruitSalad->addFruit($fruit);
// Do some assertion.
}
This creates a simple mock of the Fruit class, but I want to instantiate it via the withName() static method - and I do not want to expose a setter for the name property.
How can I create a mock for Fruit using the static named constructor?
PHPUnit used to support mocking static methods, but since PHPUnit 4.0 it's omitted. I see four options here:
1. Don't mock the method at all
You could just call the method and use it's logic, although you'd test the static method as well if you do and normally that's something you should avoid when writing unit tests.
2. Change the class
Ask yourself if this method really needs to be static and if not, change the class to test it properly. There are quite some use cases where it's better to change some of your architecture in order to write proper tests.
3. Use a spy class
Spy classes are classes that extend a class that you would usually mock, but implement some logic for testing the configuration of a class or the dependency of a tested method to another method. In the very most cases this can be avoided by mocking the class properly. Spies are simply your work around if mocks are not enough, there are very few cases in which you really need them.
However, in this case a spy could be used to overwrite a static method as a work around:
class FruitSpy extends Fruit
{
public static $return;
public static $name;
public static function withName($name) {
$expected = self::$name;
if($name == $expected) {
return self::$return;
} else {
throw new \RuntimeException("FruitSpy::withName(): Parameter 0 was $name, $expected expected");
}
}
}
This example checks for the correct $name and, if it's correct, returns your defined return. You'd use it like this in your test:
$fruitSpy = new FruitSpy();
$fruitSpy::$name = "Banana";
$fruitSpy::$return = new \stdClass();
$this->fruitSalad->addFruit($fruitSpy);
Not exactly a clean solution, but the only way I see if you absolutely positively don't want to change other code than the test code.
Again, you should think about changing the static method to a casual method if you need to do something like this.
4. Use PHPUni 3.*
You could simple use a deprecated version of PHPUnit to use this method. Not a preferred way either.
Conclusion
I don't see a clean way to mock a static method and ::staticExpects() was removed for a reason in 4.0
How can I create a mock for Fruit using the static named constructor?
You can't. Mocks are created by using a mocking framework.
Anyway it does not matter how mocks are created but, instead, how they behave, because they're external to the class being tested.
Just configure the mock so that it behaves the same way a real Fruit instance would when created using Fruit::withName.
I'm not sure if it's the proper place for such question since it's rather theoretical than the specific code sample but I'll ask anyway.
So, at some point PHP introduced type constrains in function definition (except basic types of course), i.e.
class A {
public $value;
}
function foo($someInt, A $a) {...}
What make me wondering is if PHPUnit mocks can be used in such situation:
class functionTest extends PHPUnit_Framework_TestCase {
public function testFoo() {
$mockA = $this->getMockBuilder('A')->getMock();
$this->assertEquals('some result', foo(1, $mockA));
}
}
Would such call be accepted when the test runs (ofc. I skipped includes and stuff to keep it simple).
And the more interesting question: if yes, then how is it implemented?
Yes it will be working, PHPUnit will mock your object. This mocked object will dynamically extends the base Object you want to mock.
I'm trying to get my head round Unit Testing and there's one more piece of the jigsaw I need to find.
What I'm trying to do is write tests for the following code. In this case, I've got a really simple Front Controller (written in PHP).
class frontController
{
public function routeRequest($oRequest)
{
$sClassname = $oRequest->getController();
$sMethod = $oRequest->getAction();
$oController = new $sClassname();
$oResponse = $oController->{$sMethod}($oRequest);
return $oResponse;
}
}
The problem I have is because the code creates new objects. I can easily mock the request object so that I can tightly control what it will actually do within my test case. I'm not sure the best way to actually replace the controller with a test double.
This article from IBM suggests having a factory method for creating my controller and then overriding this with a specific class used for testing:
class frontController
{
public function routeRequest($oRequest)
{
$sMethod = $oRequest->getAction();
$oController = $this->createController($oRequest);
$oResponse = $oController->{$sMethod}($oRequest);
return $oResponse;
}
protected function createController($oRequest)
{
$sClassname = $oRequest->getController();
return new $sClassname();
}
}
and then for testing perhaps something like this:
class testFrontController extends frontController
{
public function setMockController($oMockController)
{
$this->oMc = $oMockController;
}
protected function createController($oRequest)
{
return $this->oMockController;
}
}
(note this isn't quite what the article says, but I'm thinking it would be most useful to me if it did this)
Another solution could be to have another class that creates the controller. This would then be a dependent class of the frontController. This way I can replace the factory/creation class during testing with a test double. Something like this:
class frontController
{
public function routeRequest($oRequest, $oControllerFactory)
{
$sMethod = $oRequest->getAction();
$oController = $oControllerFactory->create($oRequest);
$oResponse = $oController->{$sMethod}($oRequest);
return $oResponse;
}
}
class controllerFactory
{
public function create($oRequest)
{
$sClassname = $oRequest->getController();
return new $sClassname();
}
}
I guess the dependency injection could be taken care of in the front controller constructor or via a setter instead of a parameter to the actual "route" method.
I think I prefer option 2.
Is either of these two methods the right way of going about testing this kind of thing?
(perhaps "good way" would be better word here!)
Any thoughts or suggestions on option 1 vs option 2 appreciated or indeed any alternatives. Remember - the key thing is about how to test an object that itself creates other objects as part of its execution.
Thanks!
You might find this article handy.
It discusses how object creation should be separated from the actual running of the application.
I generally find factories to be a good thing to use for this scenario. In addition to the swappability aspect, it means that additional parameters, data, or dependencies required by the object being created can be stored by the factory, and so the object which actually requests the new object doesn't have to know anything about them...
You do not want to use the real controller but a mock, right ?
It seems to me the simplest way to achieve this would be to subclass the request so that it returns the name of a MockController.
I assume you have thought through your assertions so as to define the goal of what exactly you are testing. Keep in mind that unit tests are going to be testing the returns from your methods, which, in this case, is $oResponse (whatever this may be). As a result, your test assertions will be based on this return value. Since I don't know what that return value is from your code snippets, I can only demonstrate an example that you can complete.
I would recommend PHPUnit for your testing as it seems to be the most complete package for PHP imho (many are fans of SimpleTest, as well ... to each their own).
It would look something like this (Please note that I have left out includes for brevity. Read the PHPUnit documentation for more information):
class AimTest extends PHPUnit_Framework_TestCase{
private $_controller = null;
private $_request = null;
public function setUp(){
$this->_controller = new frontController();
//what does this object's type?
$this->_request = new requestObject();
}
public function testObjectCreation(){
/*
* note, that this is only one of several assertions that could
* be made depending on the return value
*/
$return = $this->_controller->routeRequest($this->_request);
//tailor to what you expect your output to be
$this->assertTrue($return == "my expected output");
}
Hope I didn't miss the mark completely on your stated purpose. Moral of the story is that you can only test what your methods return. If you want to test object instantiation from a method, use the instanceof PHP function against a method that returns that object after instantiation.