

#Phpunit api code#
Of course, they can be really helpful while testing some big parts of code or to test if a logger has logged some information. Now I can check if adding a product is working correctly.

So I wrote a mock which is expecting that. I want to be sure that the shop will remove a product after I add it to the order. In the example above I mocked the shop which has products. You can steer how the dependencies behave or even what they return. They can control the flow of executing code. It’s a term for any kind of pretend object used in place of a real object for testing purposes. If you do not want to test every dependency in tests, you can use Test Doubles. The class below is representing an order in a shop, which you can add products to: It’s hard to prepare such a code for a unit test. Sometimes it’s very complicated and has many dependencies. Of course, the code is typically not as simple as in the example provided above. What if I pass negative numbers to increase the quantity of a product? The answer is to write a test for that: When writing your tests, think about edge cases – for example, wrong input data. I highly recommend you to start writing unit tests in this way if you are not doing that yet.ĭon’t forget about other, unhappy paths of executing our code. Thanks to that, you see what is being tested here at the first glance. The tests look much more readable and self-explanatory.
#Phpunit api how to#
You can read about how to install and run it here.

How to test it? In PHP, the most common library which helps you to do that is PHPUnit. I can increase the quantity of a product with a dedicated function for that ( increaseQuantity) : As an example, I will test a simple Product class that consists of name and quantity. I’m going to start by showing what a simple unit test looks like. The unit test doesn’t need to have the whole application stack running – you don’t need a connection to the database or anything while running them. It’s recommended to cover in your tests as many different paths as possible (and that applies not only to the unit tests but to all kinds of tests). Every test should check one path – a possible way of executing the function. Unit tests can be used for easy and fast checking business logic in the code. The unit can be a single class or a function – a small piece of code that does a specific thing.

In these, you should focus on single units in your code. The most popular type of tests that programmers write.
