How to unit test MVC classes?

I am new to unit testing in general, but wanted to implement it in an MVC pattern (using PHP). Now I'm not sure how to approach this.

Should unit testing be built into the framework or just create a new folder called tests and include all the necessary classes and unit test each of them?

In short, if there is a model M, it also has some connection with the frame itself. So, to test the model, should some parts of the structure be included in unit tests?

Are there any good code examples on how to do this.

+8
php unit-testing model-view-controller
source share
3 answers

Should unit testing be built into the framework or just create a new folder called tests and include all the necessary classes and unit test each of them?

You must create a separate folder for it. Destroying production code with tests is usually not a good idea for performance and debugging reasons.

So, to test the model, should some parts of the structure be included in unit tests?

Less is better. Unit tests should not have any dependencies. If class A depends on B , you must mock B to make sure that if B fails, it does not crash A

The main advantage of unit tests (when everything is done correctly) is that it makes it easy to identify the problem. If A fails due to its dependency B , you first look at A , then B Again, if B depends on C and C crashing, you will have to look for A , B , and then C This pretty much destroys one of the biggest benefits of unit testing. If all the tests are performed correctly, a failure in C will not crash anywhere except C , so you will have one class to look for the problem.

To really make your code a mistake, you can use unit tests in conjunction with PHP statements :

 $return = $this->addOne($some_param); assert('$return == $some_param + 1'); 

By the way, there is no difference between unit testing MVC, unlike unit testing in general.

+7
source share

Unit testing should be part of the MVC framework. For example, see the Unit Testing Class chapter in the CodeIgniter User Guide.

+1
source share

If unit testing should be built into the framework, or we just create a new folder called tests

If you use a third-party structure, it usually includes some auxiliary modules for testing modules, but you will want to put your own test classes in a separate folder so that (for example) you can turn over the release of your distribution software that does not include them.

include all necessary classes and unit test each of them?

Usually you will have one test class for each application class. So, if you have a model class M, you will have a test class M_Test (or any other naming convention that you accept.)

If you are not already familiar with PHPUnit , you will want to grab it and read your documents.

+1
source share

All Articles