| Start |
|---|
| Testing class rules Let's say, we have a simple In order to perform tests on this class, we use Unit tests (checking source code to see if it fits our expectations): How exactly Instead, if we missed one important thing and wrote this: With dozens of different rules (assuming we are using not just email and password), it's difficult to detect mistakes. This unit test: Will pass our first example but not second. Why? Because in 2nd example we wrote a pattern with a typo (missed Unit tests can be run in console with command: With additional parameters like Example how |
| PHPUnit Data Providers Test methods often need data to be tested with. To test some methods completely you need to provide different data sets for every possible test condition. Of course, you can do it manually using loops, like this: And someone can find it convenient. But there are some drawbacks of this approach. First, you'll have to perform additional actions to extract data if your test function accepts several parameters. Second, on failure it would be difficult to distinguish the failing data set without additional messages and debugging. Third, PHPUnit provides automatic way to deal with test data sets using data providers (opens new window). Data provider is a function, that should return data for your particular test case. A data provider method must be public and either return an array of arrays or an object that implements the Iterator interface and yields an array for each iteration step. For each array that is part of the collection the test method will be called with the contents of the array as its arguments. To use a data provider with your test, use Array of arraysNote that Each data set can be named for convenience. It will be easier to detect failing data: IteratorsAs you can see, simple iterator also works. Note that even for a single parameter, data provider must return an array Because if we change our Or change actual data: We'll get an error: Of course, it is not useful to use `Iterator` object over a simple array. It should implement some specific logic for your case. GeneratorsIt is not explicitly noted and shown in manual, but you can also use a generator (opens new window) as data provider. Note that So here's an example of using Note provider |
| Test exceptions Let's say you want to test method which throws an exception You can do that by enclosing the method call into a try/catch block and making assertions on execption object's properties, but more conveniently you can use exception assertion methods. As of PHPUnit 5.2 (opens new window) you have expectX() methods available for asserting exception type, message & code If you are using earlier version of PHPUnit, method setExpectedException can be used in stead of expectX() methods, but keep in mind that it's deprecated and will be removed in version 6. Syntax
Remarks
|
Read Article
https://develop.horje.com/learn/1434/reference