N
N
nepster-web2017-08-12 12:50:07
PHP
nepster-web, 2017-08-12 12:50:07

How to achieve independence in tests (phpunit)?

I'll start with a little background:
I have a layered architecture that operates with the following concepts:
Request , ViewModel , Repository , Presenter
In a few words, this can be described as follows:
- Request - makes a request to a certain data source (for example, a file, database or Api)
- Further, with the help of a certain builder, it returns a ViewModel (a class with getters)
- Presenter - a kind of wrapper over the ViewModel that modifies methods for views.
- Repository doesn't need much description.
While testing, I created a mock forRequest , palmed off certain data and began to test.
The problem turned out to be that if suddenly the test falls on the ViewModel , then this affects other tests. That is, if the ViewModel does not work, the Request , Presenter and Repository tests automatically fall .
The call chain goes something like this:
Repository -> Request -> ViewModel -> Presenter
Accordingly, if a lower-level test fails, for example Request , all tests that use this Request will fall .
I saved a lot on the test code, that is, everything seems to be tested, it can be executed in any order, but the nuance with the fall of 4 tests instead of one is doubtful.
Tell me, please, is it necessary to mock each class and write 10 times more code so that this does not happen, if so, why?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kn0ckn0ck, 2017-08-12
@nepster-web

Do not mix unit tests and integration (or functional) tests. The purpose of unit tests is to check the operation of one module (class, for example). In this case, all its dependencies get wet. The purpose of integration tests is to check the interaction of a chain of modules (services, with a database, etc.) with each other.
What you wrote looks like integration tests. Obviously, such tests will fail if something fails anywhere along the chain of modules being tested. And this is not related to the isolation of tests from each other.
That is, it would be correct to formulate the question in this way: "what percentage of unit test coverage will be sufficient for my code?" Usually stop somewhere at 70-80%
It is also obvious that 100% working unit tests do not guarantee that integration tests or functional tests will work. Therefore, it is necessary to write both.
I would not fanatically cover all class methods with tests, but only those that have high cyclomatic complexity or that are likely to change. In short, there is not much point in testing primitive/stable sections of code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question