|
|
|
| Group tests | Simple Test PHP Unit Test Framework | Partial mocks |
Mock objects have two roles during a test case: actor and critic.
The actor behaviour is to simulate objects that are difficult to set up or time consuming to set up for a test. The classic example is a database connection. Setting up a test database at the start of each test would slow testing to a crawl and would require the installation of the database engine and test data on the test machine. If we can simulate the connection and return data of our choosing we not only win on the pragmatics of testing, but can also feed our code spurious data to see how it responds. We can simulate databases being down or other extremes without having to create a broken database for real. In other words, we get greater control of the test environment.
If mock objects only behaved as actors they would simply be known as "server stubs". This was originally a pattern named by Robert Binder (Testing: models, patterns, and tools, Addison-Wesley) in 1999.
A server stub is a simulation of an object or component. It should exactly replace a component in a system for test or prototyping purposes, but remain lightweight. This allows tests to run more quickly, or if the simulated class has not been written, to run at all.
However, the mock objects not only play a part (by supplying chosen return values on demand) they are also sensitive to the messages sent to them (via expectations). By setting expected parameters for a method call they act as a guard that the calls upon them are made correctly. If expectations are not met they save us the effort of writing a failed test assertion by performing that duty on our behalf.
In the case of an imaginary database connection they can test that the query, say SQL, was correctly formed by the object that is using the connection. Set them up with fairly tight expectations and you will hardly need manual assertions at all.
All we need is an existing class, say a database connection that looks like this...
The mock version now has all the methods of the original. Unfortunately, they all return null. As methods that always return null are not that useful, we need to be able to set them to something else...
Changing the return value of a method from null to something else is pretty easy...
Parameters are irrelevant here, we always get the same values back each time once they have been set up this way. That may not sound like a convincing replica of a database connection, but for the half a dozen lines of a test method it is usually all you need.
Things aren't always that simple though. One common problem is iterators, where constantly returning the same value could cause an endless loop in the object being tested. For these we need to set up sequences of values. Let's say we have a simple iterator that looks like this...
Another tricky situation is an overloaded get() operation. An example of this is an information holder with name/value pairs. Say we have a configuration class like...
You can set a default argument argument like so...
There are times when you want a specific reference to be dished out by the mock rather than a copy or object handle. This a rarity to say the least, but you might be simulating a container that can hold primitives such as strings. For example...
These three factors, timing, parameters and whether to copy, can be combined orthogonally. For example...
A final tricky case is one object creating another, known as a factory pattern. Suppose that on a successful query to our imaginary database, a result set is returned as an iterator, with each call to the the iterator's next() giving one row until false. This sounds like a simulation nightmare, but in fact it can all be mocked using the mechanics above...
We could refine this test further by insisting that the correct query is sent...
We have a UserFinder in object land, talking to database tables using a large interface - the whole of SQL. Imagine that we have written a lot of tests that now depend on the exact SQL string passed. These queries could change en masse for all sorts of reasons not related to the specific test. For example the quoting rules could change, a table name could change, a link table added or whatever. This would require the rewriting of every single test any time one of these refactoring is made, yet the intended behaviour has stayed the same. Tests are supposed to help refactoring, not hinder it. I'd certainly like to have a test suite that passes while I change table names.
As a rule it is best not to mock a fat interface.
By contrast, here is the round trip test...
The catch is those setUp() and tearDown() methods that we've rather glossed over. They have to clear out the database tables and ensure that the schema is defined correctly. That can be a chunk of extra work, but you usually have this code lying around anyway for deployment purposes.
One place where you definitely need a mock is simulating failures. Say the database goes down while UserFinder is doing it's work. Does UserFinder behave well...?
How do we get the mock DatabaseConnection to throw an exception? We generate the exception using the throwOn method on the mock.
Finally, what if the method you want to simulate does not exist yet? If you set a return value on a method that is not there, SimpleTest will throw an error. What if you are using __call() to simulate dynamic methods?
Objects with dynamic interfaces, using __call, can be problematic with the current mock objects implementation. You can mock the __call() method, but this is ugly. Why should a test know anything about such low level implementation details? It just wants to simulate the call.
The way round this is to add extra methods to the mock when generating it.
In a large test suite this could cause trouble, as you probably already have a mock version of the class called MockDatabaseConnection without the extra methods. The code generator will not generate a mock version of the class if one of the same name already exists. You will confusingly fail to see your method if another definition was run first.To cope with this, SimpleTest allows you to choose any name for the new class at the same time as you add the extra methods.
Here the mock will behave as if the setOptions() existed in the original class.Mock objects can only be used within test cases, as they send messages, upon expectations, straight to the currently running test case. Creating them outside a test case will cause a run time error when an expectation is triggered. We cover expectations next.
Although the server stubs approach insulates your tests from real world disruption, it is only half the benefit. You can have the class under test receiving the required messages, but is your new class sending correct ones? Testing this can get messy without a mock objects library.
By way of example, let's take a simple PageController class to handle a credit card payment form...
Our interest is in the makePayment() method. If we fail to enter a "CVV2" number (the three digit number on the back of the credit card), we want to show an error rather than try to process the payment. In test form...
The call to expectOnce('warn', array(...)) instructs the mock to expect a call to warn() before the test ends. When it gets a call to warn(), it checks the arguments. If the arguments don't match, then a failure is generated. It also fails if the method is never called at all.
The test above not only asserts that warn was called, but that it received the string "Missing three digit security code" and also the tag "cvv2". The equivalent of assertIdentical() is applied to both fields when the parameters are compared.
If you are not interested in the actual message, and we are not for user interface code that changes often, we can skip that parameter with the "*" operator...
Tests without assertions can be both compact and very expressive. Because we intercept the call on the way into an object, here of the Alert class, we avoid having to assert its state afterwards. This not only avoids the assertions in the tests, but also having to add extra test only accessors to the original code. If you catch yourself adding such accessors, called "state based testing", it's probably time to consider using mocks in the tests. This is called "behaviour based testing", and is normally superior.
Let's add another test. Let's make sure that we don't even attempt a payment without a CVV2...
expectOnce() and expectNever() are sufficient for most tests, but occasionally you want to test multiple events. Normally for usability purposes we want all missing fields in the form to light up, not just the first one. This means that we should get multiple calls to Alert::warn(), not just one...
Note that we are forced to assert the order too. SimpleTest does not yet have a way to avoid this, but this will be fixed in future versions.
Here is the full list of expectations you can set on a mock object in SimpleTest. As with the assertions, these methods take an optional failure message.
| expect($method, $args) | Arguments must match if called |
| expectAt($timing, $method, $args) | Arguments must match when called on the $timing'th time |
| expectCallCount($method, $count) | The method must be called exactly this many times |
| expectMaximumCallCount($method, $count) | Call this method no more than $count times |
| expectMinimumCallCount($method, $count) | Must be called at least $count times |
| expectNever($method) | Must never be called |
| expectOnce($method, $args) | Must be called once and with the expected arguments if supplied |
| expectAtLeastOnce($method, $args) | Must be called at least once, and always with any expected arguments |
If you have just one call in your test, make sure you're using expectOnce. Using $mocked->expectAt(0, 'method', 'args); on its own will allow the method to never be called. Checking the arguments and the overall call count are currently independant. Add an expectCallCount() expectation when you are using expectAt() unless zero calls is allowed.
Like the assertions within test cases, all of the expectations can take a message override as an extra parameter. Also the original failure message can be embedded in the output as "%s".
|
|
|
| Group tests | Simple Test PHP Unit Test Framework | Partial mocks |
Documentation generated on Thu, 01 Oct 2009 20:54:11 -0500 by phpDocumentor 1.4.2