Performing unit testing with nested dependencies and Factory classes

前端 未结 2 1324
南旧
南旧 2021-02-19 01:25

I\'m new to unit testing and PHPUnit, but I\'ve reading a lot lately about design patterns and isolated tests and I\'ve decided to refactor an application I\'m working on to get

相关标签:
2条回答
  • 2021-02-19 01:43

    The factory is just like the new keyword. Do you test the new keyword? No, you test if you can construct a class. But that's independent to the factory itself and part of the unit so already part of your unit tests.

    2) is called integration testing. And you can do that with PHPUnit as well.


    Edit - As there was some discussion in comments:

    As far as Unit testing is concerned, you could unit-test your factory that it does for what it is for: return a concrete type, a type or any type at all.

    There is nothing wrong with that, however it's normally not necessary as constructors of the returned type(s) are already under unit-tests and well that test is really trivial and just data-checking which smells like integration testing. Also those types which have that type from the factory as dependency (and which are under unit-test as well) will make compilation/execution fail if the dependency can not be provided. So everything the factory is for, is already tested, even from both sides. And if the factory does not get consumed, well then you don't need to test it.

    I suggest you create once a factory purely TDD style, so to pre-formulate the use and then you'll get a feeling for this. You might want to test other aspects of your factory class(es), but probably this belongs more into integration than unit testing.

    And I don't wanted to create the impression that other of your units should actually have hardcoded calls to the factory create method(s) instead of getting the dependency injected. As you should not use new inside your units, you should not use Factory::create therein either. Similar to new, the class-name (Factory) is hard-encoded, not injected. It is a hidden dependency then. But dependencies should not be hidden; but made visible.

    0 讨论(0)
  • 2021-02-19 01:47

    You can test it with inheritance.

    Just extend House with a FakeHouse for testing, and then check $material, $door and $knob etc. whether they've changed or not after testing.

    0 讨论(0)
提交回复
热议问题