r/PHPhelp • u/Robinvb95 • Aug 09 '21
Solved Question regarding unit testing
Hi all,
So lately I've been trying to get into unit testing my code.
I think I'm ready to go and implement it, been following some pretty nice video's about it as well, however..
I'm kinda struggling to know what to test.
So the company I work for has framework that's being used to mainly power a CMS. It contains a lot of functionalities regarded to websites (create a new page, post a new blog, etc).
I can find some use cases for unit testing on specific application, but I'm kinda lost when it's for our main product..
Let's say, for example, I'd like to test our page related functionalities.
We have validation methods in place to assure that all properties are correctly filled.
I could write a test to see if the validation succeeds, but then I'd also like to create a test to see when it fails.
But, failing could be to lots of reasons!
Should I create a test for every possible reason?
Most guides and blogs related to unit testing don't do this, but I'd like to be able to have faith and trust in the test results.
I think it will also reduce bugs, but just having a test pass right now won't give me any assurance that everything is actually okay, since there are so many other possible ways to let the validation fail.
Does anyone have some experience with this, or could you share some knowledge on what to test? :)
Thanks in advance, much appreciated :)
1
u/LiamTailor Aug 09 '21
Use @dataSource to test miltiple cases the same way, but with different input data. Also try to use Single Responsibility Principle and use static calls to make writing unit tests easier.
When it comes to testing APIs, functional tests are usually quicker to write. Use mostly them, when time is short.
1
u/Robinvb95 Aug 09 '21
Thanks for the reply!
So would you recommend still testing as much variations as possible?Sometimes we create pretty complex CRM applications. These can contain processes like invoice management.
However, for some customers (customers from our client) there will be specific rules. Like, customer x will get 10% discount on product with type x, when the quotation has been accepted in 7 days.
As you might see, these rules are pretty difficult to test since our customer (the end user of the application) has a lot of customisation options in the process!
Are there specific tips for testing these situations?
I guess it all starts with writing more SOLID code, so all these exceptions could be implemented in a more structured way?
Thanks again!
1
u/LiamTailor Aug 09 '21 edited Aug 09 '21
SOLID is the way to go if you want your tests to be easy to write. Mostly it's the S (SRP). And yes, if you have the time, write tests for all possible cases. And don't forget to test null values or empty strings and arrays if they're possible to pass to a method, and to test if exceptions are thrown where they should
1
u/Robinvb95 Aug 09 '21
Awesome, thanks for your input :)
I'll add the flair solved later, I'm curious if there are other developers with another view on the subject as well! :)1
u/RealWorldPHP Aug 09 '21
I agree with the approach of testing for as many variations as possible. Having unit tests does not prove that your code won't have any bugs, it proves that your code works for the specific things you test for. So the more variations you test for, the more confidence you can have in your code. As bugs come up later on, add a test to cover that new bug.
1
8
u/nealio82 Aug 09 '21 edited Aug 09 '21
It sounds like you need to test at different layers here.
Unit tests are perfect for asserting that the logic is correct. Wherever you make a decision / have some sort of behaviour you should be unit testing. The caveat is that it's most powerful when you own all of the code inside a module. To start with, I would recommend reading 'Test-Driven Development By Example' by Kent Beck (particularly parts 1 and 3). The examples are in Java and Python, but the concepts are the same.
However, it sounds like you're working with an in-house framework (although the company 'owns' the code, it's still a 3rd party requirement to your own feature), so unit testing is much more difficult and you need to look at integration and end-to-end testing. The trouble with frameworks is that they have external dependencies (forms, databases, etc) and complexities (kernels, DI containers, etc), which are really difficult to work with in unit-land.
If you can, remove all logic from controllers and extract services / modules that you can unit test (but read the book first to show you how to do this in a TDD way!). You can still use PHPUnit for integration and end-to-end tests (not just unit), but the approach for each layer is different because each level should be testing something different about the system.
Many beginners make the mistake of testing logic and all permutations of happy / sad paths in integration and e2e tests, which are slower and more difficult to work with than unit tests, and so find testing hard and not worthwhile. There's a clear separation between the layers, which makes testing much easier to work with when you stick to it:
Unit = behaviour / logic
Integration = wiring / config
E2E = core user journeys
Expanding on these:
Any feature / logic is tested with unit tests as a self-contained module of behaviour. Make assertions on the happy and sad paths here. Make sure your code does what it is supposed to do. Write test names according to the business rule you're trying to solve, such as
an_item_can_be_added_to_the_shopping_cart, ora_single_item_cannot_be_removed_from_the_cart_more_than_once. This will be much easier to debug once tests start failing, because the test name describes what's actually supposed to happen. As you're writing the tests and implementation you'll think of edge cases and behaviours that you can add to the test class. Write them as you go.The module is wired into the framework and you use integration tests to make sure the different tech choices you make are compatible. Eg
a_shopping_cart_can_be_saved_in_the_database. You should add tests for anything which is specific to the implementation here - so checking that your shopping cart can be added / fetched from the database, or that your mailer service was given an outgoing email to handle, etc. Lots of people use this layer to test the same stuff they did at the unit test level but just using real dependencies - this is the wrong approach! If you find yourself duplicating tests between unit and integration, stop and ask yourself if there's a different approach you can use at this level.You test core / important user journeys at the
e2elevel. For example this is where multiple modules / behaviours are tested together to form one big feature, usually combining multiple steps. For example:the_customer_is_prompted_to_create_an_account_during_checkout_process_for_an_order. E2e tests generally don't test the sad path, and it would be madness to try to test every possible permutation of logic at this level. E2e tests are slow and more difficult to debug in comparison to unit tests so you want fewer of these in your system, and to prefer unit testing where possible. At this level you should be confident that the unit tests are covering your happy and sad paths, so you don't need to duplicate effort here.In your specific case, I would extract some sort of validation class or module, and I would make sure I cover this with unit tests. The controllers can call that module. This layer of testing would make sure that the validation allows suitable values to pass and that invalid values don't. Be specific with test names. If a particular value is supposed to fail in a test, make sure your test name explains why.
Examples of what I would regard as appropriate / good test names in a validation module test class (each test name is descriptive of what the expected behaviour / business rule is):
validation_is_successful<- this is where all properties pass validationthe_email_address_must_be_valid<- here i would assert that an invalid email address fails validation. maybe i would go through a few different example invalid email addresses (see data providers in PHPUnit). I would not check a valid email address in this test, because that is already covered in the successful test abovethe_phone_number_must_be_valid<- here i would throw some invalid phone numbers into the validator and make sure validation did not pass. phone validation can be complex and might even become a module of its own, in which case i would move the phone validation tests from here into the phone validation moduleExamples of poor / lazy test names:
all_parameters_are_correct<- this isn't the worst example, but there's no indication in this test name of what we're expecting the behaviour to bethe_object_can_be_constructed<- this test would be useless. your focus should be on testing the behaviour of your module / feature, not implementation detailtest_get|set_[x]_property<- testing getters and setters means you're not thinking about your system's behaviour, but rather how your object looks. tests are the most flexible / enjoyable / easiest to maintain when they describe behaviourall_properties_fail_validation<- this test would be testing too much in one go. if it failed there'd probably be no easy way to find out exactly what went wrong2. You might not even need an integration test for this, unless the form is saving to a database. If it is, I would write an integration test that calls the module directly, and make sure that some database row got inserted / updated / whatever
3. For the e2e test, I would call the controller in some way (api, web crawler component, however your framework handles it) and make sure that my account was created and I received an email with a login link, or that my billing info was updated, etc.
I did make a video introducing TDD (covering unit and integration testing) for a conference recently. I had to pre-record because I was moving house on the day of the conf, but feel free to watch it here: https://www.youtube.com/watch?v=UN6IjakLPpI. It's kinda fast-paced because I had a lot to squeeze into a 30 minute gap, but I go from installing PHPUnit as my first dependency to building a shopping cart and wiring it in to the framework, and covering the MySQL-specific behaviour with integration tests.
Don't forget to buy the book!