Thoughts About Unit Testing | Prime Reacts

  Рет қаралды 243,168

ThePrimeTime

ThePrimeTime

Күн бұрын

Пікірлер: 501
@tiskahar9738
@tiskahar9738 Жыл бұрын
the irony of listening to this while actively writing mocks and excessively unit testing
@Kalasklister1337
@Kalasklister1337 Жыл бұрын
just today i wrote a single test with three mocks in it...
@SaHaRaSquad
@SaHaRaSquad Жыл бұрын
The things we do to try staying sane.
@liquidsnake6879
@liquidsnake6879 Жыл бұрын
@@Kalasklister1337 No idea what's the problem with that, if the shit is not in your unit under test it should be mocked. Otherwise, you're testing other people's code and making your own tests flaky since they no longer test just your implementation but also other people's implementations on top
@TakenPilot
@TakenPilot Жыл бұрын
When I write mocks, I do it in Rust.
@TheStickofWar
@TheStickofWar Жыл бұрын
@@liquidsnake6879yeah there is no problem with it, people should remember that here isn’t the word of god
@bobbycrosby9765
@bobbycrosby9765 Жыл бұрын
These blogs always pick an easy example. Most validation also requires examining the database. A common one would be, in this scenario, a requirement where user email address needs to be unique.
@michaeltruong405
@michaeltruong405 Жыл бұрын
That’s a good point
@Adowrath
@Adowrath Жыл бұрын
This also somehow assumes you will never forget to call that validate function before putting it in the database -- solve one problem (testability) while creating another (reliability).
@MikeZadik
@MikeZadik Жыл бұрын
yeah well. Just put a list of all users in as parameter. There problem solved. Skill issue /s
@Adowrath
@Adowrath Жыл бұрын
​@stevemartin2981How would a Factory help with validation that depends on context stored in the database?
@Adowrath
@Adowrath Жыл бұрын
​@stevemartin2981That doesn't answer the question, now does it. You can make the fanciest factory pattern, without using the database you cannot enforce constraints that require data stored in the database.
@pdwarnes
@pdwarnes Жыл бұрын
I find a lot of mocking comes from arbitrary code coverage percentages (80%-100% unit test code coverage). Also seen with: "unit test confirms exact log output", and "unit test getter/setter/properties".
@ScottLovenberg
@ScottLovenberg Жыл бұрын
My favorite part of arbitrary code coverage percentage is when you add something small with a test but still don't have enough coverage. Naturally you add a test to some code you didn't write using doc tags and comments to guide writing your test. At this point you find out the code or documentation has always been bugged and just make the test match the current output. Now the tests make fixing the bug a regression. And all I wanted to do was add a feature that scratches an itch I have or upstream patches I'm sitting on.
@Jeryagor
@Jeryagor Жыл бұрын
I was going to say this as well: mocks are needed when unit tests are expected to cover 80+% of your code by company policies. :) I wouldn't say they test nothing like the article though: you can still do some checks on inputs, control return values and errors... which can be useful to some extent.
@CottidaeSEA
@CottidaeSEA Жыл бұрын
@@Jeryagor Covering 80+% of the code is just crazy to begin with. Particularly if you're using an ORM. Your database queries should be automatically tested, which means only the logic parts (the fiddling) need testing that, lo and behold, shouldn't need mocks if written well.
@Alex-lu4po
@Alex-lu4po Жыл бұрын
@@CottidaeSEA You still have to somehow test if your ORM returns the things you expect depending on the ORM, e.g. Laravel's Eloquent can also be used as a Query Builder and so you might want to ensure that the correct data gets returned...
@liquidsnake6879
@liquidsnake6879 Жыл бұрын
If people are mocking their own code, then they're doing it wrong, simple. Mocks are for things outside your unit-under-test exclusively, everything within your code should be tested and anything outside it should be mocked. Even if it's a database query, you might not test the DB query itself (your ORM handles this), but you definitely want to make sure your ORM command is requesting the right data. So you'd mock the ORM itself and check that people are making the right query to it and including all the things you expect
@noherczeg
@noherczeg Жыл бұрын
5:41 well that works until you find a compatibility issue because not all features are ported to SQLite in the exact same way as what PG did.
@HrHaakon
@HrHaakon Жыл бұрын
You mean, any non-absolutely-trivial thing? I completely agree with you. I've mostly worked with Oracle, but have used PSQL a lot too, and things that I know are different in Oracle and SQLite are: - Text vs varchar2, clob and char have different semantics, and Oracle infamously treats "" as null. This is kinda important that your program picks up on... - integer types are different, and Oracle has a number that includes support for decimal numbers, which you don't want to have truncated to ints, or screwed up to 64-bit longs. - date handling is pretty different, Oracle supports julian days, ISO strings and unix time, but: Every DBA I've ever known have broken out in sweat if you don't specify the date format in Oracle first. Why wouldn't you document your intention? - floats are 126 bits in Oracle, 64 in SQLite And that's just the basic datatypes. SQLite is cool, I have nothing against it in any way, but it's not a great way to test against your database. Use the free version of the database for that. Oracle, Microsoft, even PostgreSQL offers free versions of their databases that are really useful as testing tools. (Yes, the psql mentioned was a joke. I know it's all free.)
@dejangegic
@dejangegic 28 күн бұрын
Yeah that's why over-abstraction is usually the devil
@AJMansfield1
@AJMansfield1 Жыл бұрын
For testing library-type code (e.g. data structures) in dynamic languages, mocks can be useful for verifying that your fancy data structure isn't accidentally doing something untoward with the objects you're entrusting to it -- you can verify that only functions that are part of the interface that algorithm requires are called, and that things that are part of only _most_ objects (e.g. random toString logging calls) aren't used.
@trumpetpunk42
@trumpetpunk42 Жыл бұрын
I know you said dynamic languages, but this all seems like non-problems that the compiler should enforce
@kaanatakan
@kaanatakan Жыл бұрын
There is a valid use case for mocked APIs: One time I was writing a shipment tracking service and it would connect to the API's of various shipping providers and check the status of packages and trigger notifications to users devices. While some of the shipping companies provided testing servers they didn't update the package status since there was no actual package and no real delivery process. So I couldn't use the actual API even if I wanted to. Instead I created a series of responses and stored them in a bunch of files. Then I served these files iteratively. A big benefit is that your test can go real fast without the network latency. But you have to maintain the mocked responses which is kind of a bummer.
@jimiscott
@jimiscott Жыл бұрын
Perfectly valid - there are all sorts of scenarios such as this where you a. cannot call the service as it would trigger a real event OR you cannot call the service as it simply would not act the way you need to test. As you've mentioned you need to keep the response files and serve these up - a common pattern and there are frameworks that do exactly this ... wiremock for example. Is this a unit test or an integration test? Does it matter? I feel we waste too much time classifying these types of things when all you're trying to do is validate the system.
@adriankal
@adriankal Жыл бұрын
Normally those kind of services do have sandbox modes where you can test your code against the real backend. If they don't have it maybe it's good idea to look for alternative.
@kaanatakan
@kaanatakan Жыл бұрын
@@adriankal Did you read my comment? A few of them had a sandbox but they didn't bother to simulate someone scanning the packages barcode at various locations it was insufficient for the purposes of the tests I had to run. And I couldn't just say oh well I guess I wont use DHL or UPS. I had to deal with much smaller shipping companies that didn't even have a test database. I would have to test those with real tracking numbers.
@antdok9573
@antdok9573 Жыл бұрын
So contract testing. That's pretty much the only reason to mock. APIs should be contract tested at a minimum, unit tested if its your API
@bionic_batman
@bionic_batman Жыл бұрын
Making your tests depend on the API that you do not own is pretty bad idea and imo I would take mocks over direct API calls in this situation any day. Especially if you run those tests in CI/CD pipelines. Pretty interesting that you've mentioned shipping providers btw, the company where I work also deals with those and mocks (such as gomock or httptest libraries) are actually invaluable for our needs, there is no other way to ensure that your code is not going to break and your tests are not flaky Also sandbox APIs that shipment providers have usually either don't work half of the time or just break quite often.
@PhillipDressen
@PhillipDressen Жыл бұрын
The first time I heard about JavaScript on the back end, I laughed thinking it *was a joke*... I don't regret how hard I laughed
@BittermanAndy
@BittermanAndy Жыл бұрын
Right? I absolutely agree it would be awesome to use the same language throughout the stack... but who thought JAVASCRIPT should be that language???
@kairo1502
@kairo1502 Жыл бұрын
I highly recommend reading "Unit Testing Principles, Practices, and Patterns" by Vladimir Khorikov. It's probably one of the best software design books.
@mackomako
@mackomako Жыл бұрын
Thank you!
@VideoWow7184
@VideoWow7184 Жыл бұрын
Yep, read that one, it's really good.
@darkdreamflyer2317
@darkdreamflyer2317 Жыл бұрын
Bwhahaha. I second that. For years i am all the time recommending this (Khorikov) book to any person at first opportunity to get started with unit testing. (And then recommending TDD Kent beck as second book, for more practical approach, with learning feeling how much pause can be allowed between written working code)
@JonathanKramer-g1c
@JonathanKramer-g1c Жыл бұрын
Hey Prime, not usually a commenter but I think this hate towards mocking is misleading to newer devs. Overall love the advice on code structure. Would really appreciate a response to the below :) In the example in the article there is a critical piece missing about how to glue things together. This is a transitive problem at each level of abstraction (normally several of these in any large code base), and these glue layers often contain small bits of logic themselves. Also, not all dependencies are deterministic (i.e. http timeouts, db trx contention, etc.) and it can be useful to model these situations to verify your code behaves as expected (i.e. propagating the right errors or retrying a certain way) For example, consider a common API handler function: 1. Stateless request validation (pure function) 2. Fetch some data (function with network dependency) 3. Stateful validation (pure function) 4. Example Twiddle: Some type mappings between request domain and data domain (pure function) 5. Store some data (function with network dependency) 6. Map stuff to a public facing response (pure function) This "glue function" has logic as to how it fulfils these steps and deals with potential failures (i.e. if we fail a validation step, further functions should not be called). When it comes to testing this, I want to test the wiring logic WITHOUT rehashing the behaviors of each of the dependent functions. I could do this by "injecting" my various dependent functions as well typed parameters and then "mock" the behaviors such that I can ensure certain branches get hit. This is all decoupled from the implementations; I can change the validation logic and it doesn't change the test. Call it mocks and DI or call it function composition, its all the same at the end of the day. You might argue all the glue branches get covered by integ tests, but this is almost never true at scale. These UTs are so easy to write too and in my experience have huge ROI for mature code bases.
@mortens583
@mortens583 Жыл бұрын
was thinking the same think, I fully agreed on seperating "statefull" and pure logic, but testing the seperated statefull logic is still worth it imo
@andrueanderson8637
@andrueanderson8637 Жыл бұрын
3. Stateful validation --- This is where you messed up. Parse, don't validate. Especially if you're doing HTTP requests to third-party services on the server side for some reason. This makes your "wiring" completely deterministic and testable. 5. Store some data --- Testing this is pointless, if a third-party dependency fails there's nothing you can do about that. The best approach is to branch the computation into two deterministic functions and test them both in isolation.
@doktoracula7017
@doktoracula7017 Жыл бұрын
@@andrueanderson8637 You have different understanding of "parse" and "validate" than I do. Could you explain what's the difference? >Especially if you're doing HTTP requests to third-party services on the server side for some reason Yes I do, how you'd otherwise save data in user country first to follow GDPR? Do everything asynchronously (obv bad idea)? What if you're using external secret managers or anything that is complex and you don't want to write your own code for? >if a third-party dependency fails there's nothing you can do about that Yes you can. You can use alternative mechanism on failures (instead logging to monitoring services you write to file), you might retry or anything else. Most of time those are just unimportant details, but in some cases they're important. Things are not always deterministic unless you live in haskell land. >branch the computation into two deterministic functions and test them both in isolation How you'd do this with saving info to database? Anything that deals with real world won't be deterministic, unless by deterministic you mean "I know what happens if saving fails and I know what happens when saving works and both cases are tested"
@forzaarden
@forzaarden Жыл бұрын
totally agree with this, you want to test things without relying on your dependencies that, in integration envs, are often broken. Of course you want integration tests, but that doesn't mean you don't want functional tests that tests your service functionality mocking all your deps. The example in the article is too trivial, and even if you can relate for simple unittests, it doesn't work when layers of abstraction start to grow. And btw it's 100% better(for dev confidence) to have functional tests that work 100% of the time with mocks, to have integration tests that work 85% of the time because of network/database/other services issues independent from your service.
@aaryfn
@aaryfn Жыл бұрын
Yeah, I don't get the hate for DI & mocking. In my experience a sufficiently large codebase will have things that have tons of dependency. The only feasible way to test them is using DI & mocks. Mocking is akin to doing experiment where we assume everything else is correct & test with that assumption in mind.
@shanebenning
@shanebenning Жыл бұрын
“… fixed TypeScript’s biggest problem” is the summoning ritual for Matt
@tech3425
@tech3425 Жыл бұрын
Exactly what i thought 😂 If you say you've fixed a language's biggest problem...then you're Matt Pocock
@DrPizza92
@DrPizza92 Жыл бұрын
What’s up wizards?
@TeaBroski
@TeaBroski Жыл бұрын
you gotta appreciate the Ryan George "super easy, barely an inconvenient" quote
@NyaowYeon
@NyaowYeon Жыл бұрын
Thanks
@ThePrimeTimeagen
@ThePrimeTimeagen Жыл бұрын
WOAH!! a super. ty ty
@ClaytonHarbich
@ClaytonHarbich Жыл бұрын
I'm a desktop developer and disagree with this. Testing a desktop application without mocks is a nightmare hellscape where there is no return. I understand that backend is different but there are many more dependencies in this world other than db. What about calling other API's, report generation, interfacing with other applications or any of the many scenarios that would break a unit test without a mock?
@portusdelphini
@portusdelphini 4 ай бұрын
Backend unit testing without mocking is a hell.
@fennecbesixdouze1794
@fennecbesixdouze1794 Жыл бұрын
I love Go's named returns. Keep in mind you absolutely don't have to use them naked. They are extremely useful as quick bits of documentation if you have helpful names for the return variables, especially if you are returning more than one variable of the same type. They also really help with reducing complexity because they guarantee those variables will be declared at the very top of scope, which can really help with refactoring and reasoning about the function. Kind of like defer guaranteeing stuff happens before exit, it makes it easier to write and refactor code while maintaining guarantees that your declarations haven't been moved around and caused some insidious bug. Even naked returns with stuttering names like "err error" can be very useful in private implementation code and should be used freely there. The only caveat with naked returns is don't add stuttering named return values in public methods: your public methods are primarily meant to be understood by the people using them, and stuff like (string string, err error) adds needless complexity to reading the function signature.
@jamesm4957
@jamesm4957 Жыл бұрын
so which is more idiomatic go? is it both?
@HonsHon
@HonsHon 8 ай бұрын
I do use them while being naked tbh. In fact, most languages in general I program while naked
@bscharbau
@bscharbau Жыл бұрын
How do you now test that the validation is actually performed before saving anything to the database without using a real database or mocks?
@ripple123
@ripple123 Жыл бұрын
as someone who uses C# professionally, why the fuck does someone want exceptions and try/catch in go? errors as values are far superior to debugger’s jumping in catch block at the slightest hint of trouble
@banatibor83
@banatibor83 Жыл бұрын
till you have one or two errors. When you have to handle 5+ probable errors your code becomes ugly.
@AJ213Probably
@AJ213Probably Жыл бұрын
@@banatibor83 but is it better trying to handle 5+ probable errors that you don't know?
@angelocarantino4803
@angelocarantino4803 4 ай бұрын
​@@AJ213Probablyit's better to have the best of both. Options for the win :)
@AJ213Probably
@AJ213Probably 4 ай бұрын
@@angelocarantino4803 Yeah basically. I am heavily using Rust nowadays and Options are great. Though in the context of Godot Rust I need to use expect() instead of unwrap() since the debugging can be pretty bad there. I have learned my lesson and will now use expect instead lol
@axelfoley133
@axelfoley133 Жыл бұрын
4:05 One doesn't simply insert Screen Rant memes into dev content. Bootdev: Actually it's super easy. Barely an inconvenience.
@sutirk
@sutirk Жыл бұрын
Im gonna need you to get alll the way off his back
@bootdotdev
@bootdotdev Жыл бұрын
OH REALLY
@Evan-dh5oq
@Evan-dh5oq Жыл бұрын
It's definitely tight
@axelfoley133
@axelfoley133 Жыл бұрын
@@sutirk ok well let me climb off that thing
@Patrick_Bard
@Patrick_Bard Жыл бұрын
yeah yeah yeah
@ScottLovenberg
@ScottLovenberg Жыл бұрын
Yo dawg, we heard you like mocks....
@Thomas_Lo
@Thomas_Lo Жыл бұрын
...so we mocked your mocks.
@spl420
@spl420 Жыл бұрын
​@@Thomas_Loso you can mock your mocks while you are mocking your mocks.
@bootdotdev
@bootdotdev Жыл бұрын
LOVE TO SEE IT. Thanks for the read Prime
@SkillTrailMalefiahs
@SkillTrailMalefiahs Жыл бұрын
You have excellent articles bro!! :D
@bootdotdev
@bootdotdev Жыл бұрын
@@SkillTrailMalefiahs yoooo thanks
@moraigna66
@moraigna66 Жыл бұрын
I was taught mocking in school, it made a lot of sense to me. You want to decouple the code in tests. If module A depends on module B, you unit test B, then mock B for A's unit tests. That way, if a dummy breaks B, only B's tests fail and it's way easier to find the bug than if all tests fail together. Also, mocking is a necessity in Test Driven Development. Not saying if TDD is a good idea or not, I really don't know. It's a good exercice though.
@jimiscott
@jimiscott Жыл бұрын
Yep - Fine with mocks - particularly on complex systems - yes they can get complex.
@Qrzychu92
@Qrzychu92 Жыл бұрын
it depends, if your assert at the end is "function X was called exactly 2 times with following parameters", then it doesn't bring that much value. I prefer to mix in a bit of functional programming - all the "logic", like validation, actually modifying the data etc lives in public static functions (not async if you language support async/awawit). Async means you are doing something - db call, network call etc. You unit test the pure functions, without any mocks. Then you integration test the big async functions that call the db (TestContainers are awesome for that), and only check if the output matches the expectations for the input - nothing else. That way you know it works, and you can easily change implementation, while unit tests are keeping the internal contracts intact
@jimiscott
@jimiscott Жыл бұрын
@@Qrzychu92 There is (like everything) some validity in asserting that a method on a mocked property is called exactly X times....not all the time, but some times.
@epiicSpooky
@epiicSpooky Жыл бұрын
If "B" breaks, that should have been caught by B's tests before it was even submitted. If it wasn't caught, it's good your tests are catching it and now blocking your release of a broken product.
@Anim4us
@Anim4us Жыл бұрын
If you have to use TDD, just write an integration test rather than a unit test. I don't understand why TDD advocates don't seem to think that's a good idea, or don't advocate for it over unit tests where it is useful.
@misskalkuliert3976
@misskalkuliert3976 Жыл бұрын
Hello Prime, i dont know if you are ever going to read this, but as someone who just finished learning this job for two years in germany and tries to find her way through all this content and all, you are a great help. As a trainee didn't learn much of programming. I was basically just prepraed for the exams and that is about it. Your content helps me. If you or anyone here has some kind of help for me to what learn first and what I need to know, it would be sooooo helpful
@lol785612349
@lol785612349 Жыл бұрын
Kinda same here. Did you find something?
@MrDasfried
@MrDasfried 8 ай бұрын
Start writing small apllications for yourself/to learn/get projects done, would be my idea...
@theherk
@theherk Жыл бұрын
Many great points from you, the article, and many comments, but I don’t think mocks are a problem *if* you prefer, as I do, to test only public interfaces. Those in some cases while actuating underlying code, will need to call outside the library which shouldn’t happen in unit test. Mocking should be done only when necessary, but it is sometimes.
@jeromesnail
@jeromesnail Жыл бұрын
Great advice if all your functions are independent. It might be the case of 1% of all written code.
@chiefxtrc
@chiefxtrc Жыл бұрын
But what if the "filddling" part requires querying the db for example? Maybe I need to validate something against some configuration or value not already in memory. Even if I'm not making external calls, I might call some other internal module which I then need to isolate from the system under test. Domain logic can still have dependencies which need to be mocked. What am I missing here?
@OrbitalCookie
@OrbitalCookie Жыл бұрын
If it's actually backend that has to serve responses ASAP, you have 3 things besides fidling logic: existing data, an update info, and what needs to be updated. All can be represented by simple structures. (Existing Data + Update Info) feed into fiddling logic, which spits out (What needs to be updated). What needs to be updated is a structure, you can test it. Or you can run all necessary queries to do what "What needs to be updated" structure says. There are always exceptions of course, and that's normal. In those cases mocks are fine. All absolute "rules" in development are bad.
@chiefxtrc
@chiefxtrc Жыл бұрын
@@OrbitalCookie okay, so domain logic or "fiddling" would need to keep no dependencies of its own and get everything it needs via function arguments? So it would be made up of pure functions with no state. That's fine but then the definition of domain logic from the article no longer applies since there may be an arbitrary number of abstraction levels within it that have their own separate fiddling and side effect parts. So if you still want to avoid mocking you would only be able to test the pure parts but not the stateful parts that use them, since those would be considered integration tests, even though they're part of the domain logic, leaving holes in the test coverage at different levels. I would just avoid mocking that validates against implementation, to avoid coupling the tests to it, but stubbing dependencies within domain logic should be fine imo.
@drknoba
@drknoba Жыл бұрын
100% agree! Mocks are a great way to fk up your test suite. Where i work, my boss mocked all his internals and taught the rest of the engineering team to do it. I never gave in. After he left i was finally able to convince the team to stop doing it. Your test should describe a narrative on how it behaves, not how it’s implemented.
@Milotiiic
@Milotiiic Жыл бұрын
How would you approach testing a function with multiple dependencies, where the code execution takes different paths based on various conditionals? The function's behavior might change if, for example, a validation step fails or if an HTTP request encounters an error so further code may not be executed but other will still be executed. I want to ensure comprehensive testing to cover all possible scenarios. Given the complexity and potential branching, how would you design tests to verify that the function behaves correctly in different conditions? I don't think its possible to achieve this without relying on mocking
@alexaneals8194
@alexaneals8194 Жыл бұрын
The one area I like to use mocks is to put the code in an unexpected state and see if handles the error and that it gives a reasonable error message. If the program is logging errors then I will mock out the logger to catch the error directly and compare it to what is expected rather than actually write the error to log. The other area is when I have to fix legacy code and I need to mock out the stuff that is irrelevant or that is creating expensive connections. Sometimes you can break the code out into a separate function and not have to mock it, but I have run into cases where that's not possible without a major refactoring of the code.
@LEGnewTube
@LEGnewTube Жыл бұрын
I think mocks are useful when your functions make calls to third party things. Like for example if you have a route that does some stuff and makes a call to an email client. You have to mock the email client response because you shouldn’t actually be calling a third party service in your unit tests.
@samanthaqiu3416
@samanthaqiu3416 Жыл бұрын
ideally you shouldn't be calling random third party things directly in the backend call, these things can be scheduled with a message queue, then the test only needs to test that an event for email notification is in the test queue
@LEGnewTube
@LEGnewTube Жыл бұрын
@@samanthaqiu3416 not always. There’s lot of scenarios where you need to call third party services because you need data from them that is later used in your func. You can’t put that in a queue.
@ashvinnihalani8821
@ashvinnihalani8821 Жыл бұрын
I guess in that case shouldn’t the data manipulation be separate out in its own function that way the main function shoud be 1) preprocess data logic 2) third party call 3) post process logic Thant was you can actually unit test 1 and 3 and save running the full function with a test enviroment with integ tests
@ashvinnihalani8821
@ashvinnihalani8821 Жыл бұрын
A more accurate statement would be you shouldn’t mock in unit tests
@LEGnewTube
@LEGnewTube Жыл бұрын
@@ashvinnihalani8821 Sure, but if you need to test the whole flow of the main function than you would need to use a mock.
@kezzu5849
@kezzu5849 Жыл бұрын
Shout out to the author for using "Super easy, barely an inconvenience" 😂 Pitch Meeting has reached the far reaches of the internet 🙏🏿
@pycz
@pycz Жыл бұрын
Here's how I prefer to test my backend handles: 1)I use Docker (specifically docker-compose) to run an ephemeral database just for tests. 2)I create the database and run migrations at the start of the tests, and then destroy the container when they finish. 3)I test HTTP requests to a handler, which allows me to refactor the inner logic of the requests later. It's not exactly unit testing, but it works fine, especially in the microservice world.
@jarosawsmiejczak1138
@jarosawsmiejczak1138 Жыл бұрын
@pycz I think this approach is pretty standard in e.g. Django ecosystem, because there are a lot of places using a database (Models etc.). That line between integration and unit-testing is very thin in such cases.
@SR-ti6jj
@SR-ti6jj Жыл бұрын
@@jarosawsmiejczak1138 Rails takes a similar approach iirc
@smallfox8623
@smallfox8623 Жыл бұрын
testcontainers is great for this case
@QckSGaming
@QckSGaming Жыл бұрын
That's just a normal integration test. Unit tests test code of units. Integration tests test code that need external units (database) you cannot test (database engine)
@chauchau0825
@chauchau0825 Жыл бұрын
⁠@@QckSGamingI realize in recent years that most people in this industry don't even understand the basic difference between unit test and integration test.
@asdfasdf9477
@asdfasdf9477 Жыл бұрын
No pgcrypt, clientside timestamp and hashing, no RETURNING id, no error handling (duplicate email? or transient error, so gotta retry?), no prepared statements, timeouts, stats collection. We don’t even look at the response. So what do we do? Extract two of the four non-db-related steps into a separate function of course! Now we’re cooking on gas! No need to run expensive integration tests to test those 2 ifs! The main problem of the project has been solved.
@Milotiiic
@Milotiiic Жыл бұрын
How would you approach testing a function with multiple dependencies (database service, logging service, http request service, etc), where the code execution takes different paths based on various conditionals? The function's behavior might change if, for example, a validation step fails or if an HTTP request encounters an error so further code may not be executed but other will still be executed. I want to ensure comprehensive testing to cover all possible scenarios. Given the complexity and potential branching, how would you design tests to verify that the function behaves correctly in different conditions? I don't think its possible to achieve this without relying on mocking those dependencies, or at least i can't figure one out
@KlemensSoftware
@KlemensSoftware Жыл бұрын
Keep in mind, that while using SQLite for testing is great, it does not share all features with postgres. So then you have integration tests, which use different database than your production environment. I would sleep better at night, if the testing DB engine is the same as the production one :)
@DensityMatrix1
@DensityMatrix1 11 ай бұрын
Docker solves this. Most languages have some integration with test containers, if not, it’s straightforward to roll your own.
@se4geniuses
@se4geniuses Жыл бұрын
Remember the old adage, “Use the right tool for the job.” Mock is just another tool in the development and testing toolbox. The bigger problem in the examples was the poor design of the system, coupling data validation to the save function.
@alexsmart2612
@alexsmart2612 Жыл бұрын
Great that you separated out your validation logic and wrote unit tests for the validation logic. But how do you validate that your http handler is actually calling validation logic at all? Surely not as part of your end-to-end tests?
@nryle
@nryle Жыл бұрын
Tests don't test current code. Tests test future changes to your code. Your tests are bad if your mocks are able to hide future code changes. However, you can use them to also assure that future code changes don't break the expectations of current code.
@peachezprogramming
@peachezprogramming Жыл бұрын
as an aspiring backend dev, I am so happy i understand this
@terjemahanminda-ahmadfahmi6343
@terjemahanminda-ahmadfahmi6343 8 ай бұрын
hi, we have this situation. front end and back end is on separate team. in achieving the given timeline, development have to be in parallel, which means front end have to "imagine" what backend will response. Not applying mock in the backend for the consumption of front end will cause the delay in development time for front end. Therefore, I see the importance of having mock API. what's your thought on this?
@RoadToStrength-nv8ei
@RoadToStrength-nv8ei 7 ай бұрын
But in your scenario that's just the backend providing dummy data so that the frontend can iterate simultaneously. That's not related to testing, that's implementation right? Unless I am misunderstanding something.
@terjemahanminda-ahmadfahmi6343
@terjemahanminda-ahmadfahmi6343 7 ай бұрын
@@RoadToStrength-nv8ei your understanding is correct. but I don't understand why do you say it's an implementation? it's still within development phase. or maybe I misunderstood on mocking API. I'm new to automated software testing.
@RoadToStrength-nv8ei
@RoadToStrength-nv8ei 7 ай бұрын
​@@terjemahanminda-ahmadfahmi6343 What I understood from your post was that the frontend needed some sort of data from the API so that they can work on features at the same time that backend is working on the API so that frontend isn't blocked and everyone can work simultaneously. If that's the case that's not related to testing right? They're working on implementing a feature using dummy data. Once backend is done, frontend will just update the endpoint to get real data. So I guess I don't understand how that's related to testing. Then again I could be misunderstanding something
@zevo92
@zevo92 Жыл бұрын
1:36 minutes into the video, am already very much entertained. I love this man :X (Disclaimer: In a very platonic way)
@marcgentner1322
@marcgentner1322 Жыл бұрын
Then how would you structure your codebase? Filestructure and MVC logic? Please inform me on whats a good way to develop a let's say a Rust http service?
@vytah
@vytah Жыл бұрын
90% of our test code is integration tests, and CI has to install MariaDB in the container. The main reason is that the code is ass, but the second is that there's tons of MariaDB-specific code that would simply fail on Sqlite or H2 and wouldn't be tested at all if we used mocks for everything.
@ivanovichru510
@ivanovichru510 Жыл бұрын
Love the Ryan George "Super easy, barely an inconvenience".
@tongobong1
@tongobong1 Жыл бұрын
When you said "never mocker" I pressed the subscription button and I have just around 10 subscribed channels after using youtube more than 10 years.
@marcbotnope1728
@marcbotnope1728 Жыл бұрын
Check your unit tests privilege! Some of us are happy if there are any automated testst at all.
@askolotus_prime
@askolotus_prime Жыл бұрын
:D
@autohmae
@autohmae Жыл бұрын
8:44 don't specifically need ORM, just an encapsulation function to not do it raw. A function which generates the SQL.
@WindupTerminus
@WindupTerminus Жыл бұрын
Meanwhile I had the joy of finding some tests in the java codebase at work where the database is mocked, and the database mock returns a mock of a plain java object. Sometimes I wonder where people got the idea that the new keyword is an antipattern
@ThePrimeTimeagen
@ThePrimeTimeagen Жыл бұрын
hahahaha
@ThePrimeTimeagen
@ThePrimeTimeagen Жыл бұрын
also sorry
@HrHaakon
@HrHaakon Жыл бұрын
At a guess, the constructor/factory had some logic in it that talked to something, and used the results to get the object. Is that stupid? Yes. But that's what a lot of people did. Hey, a constructor is just a function right? The opposite idea is called IoC or DI: It's the idea that if your object needs say, a DAO (those things that prevents @ThePrimeTimeagen from having to make 10kloc pull requests because a data service changed), you go and get the DAO, and then hand it to the constructor. The constructor does not go out and do things. The object after it's constructed should to the extent it's reasonable not go and find things to talk to. Those things either get injected into it (through say the method call, or the constructor if it's used many times), or those things go and talk to the object. The whole injection framework thing should not be confused with the concept of DI as a coding style. They're two very different things.
@WindupTerminus
@WindupTerminus Жыл бұрын
@@HrHaakon Not at all, in this case it was a simple Spring Data JPA repository like public interface SomeRepository extends CrudRepository { public MyEntity findBySomething(Long value); } public class MyEntity { private Long id; private String someProperty; // Setters and stuff } And a test like void test() { var repo = mock(SomeRepository.class); var entityMock = mock(MyEntity.class); when(repo.findBySomething(anyLong()).thenReturn(entityMock); when(entityMock.getSomeProperty()).thenReturn("Hi!"); var service = new MyService(repo); var entity = service.getById(17); assertEquals("Hi!", entity.getSomeProperty()); }
@mlntdrv
@mlntdrv Жыл бұрын
@@WindupTerminus your example uses DI (repo is injected into service instead of service creating repo via new Repo) and not the new keyword, so not really sure what you wonder about.
@krccmsitp2884
@krccmsitp2884 Жыл бұрын
I love all of it, from the article and your reaction. 🙂
@BorisTheDev
@BorisTheDev Жыл бұрын
I wanted to skip the video when I heard “never mock”, but didn’t… and in the end the final thought was not to use mocks for integrated tests. And here are I 100% agree with you. But I do think that mock is a powerful tool for state testing. And to be honest you need to test the contracts and the states. If both are tested you don’t even need integrated tests.
@spicynoodle7419
@spicynoodle7419 Жыл бұрын
I only mock things that make http requests to external things like google services. 99% of the time you don't need a real response from google to test. Everything else is fileld with fake/incorrect/empty data, with a real database.
@banatibor83
@banatibor83 Жыл бұрын
That is the only time when you have to mock in a well designed system, when you need to fake responses from outside your code.
@alanonym8972
@alanonym8972 Жыл бұрын
That would be the one thing that I wouldn't mock, to be sure that the interface did not change from their side and to keep up to date with them
@spicynoodle7419
@spicynoodle7419 Жыл бұрын
@@alanonym8972 if their APIs aren't versioned or they make a breaking change without announcing it months prior, your production will crash regardless of your tests. So there's no reason to test 3rd-party services.
@alanonym8972
@alanonym8972 Жыл бұрын
@@spicynoodle7419 I mean it does not necessarly crash, it might just not work as intended. It is also not necessarily a bug that will be detected immediately by your users, or maybe they won't really report it for some time. I have spotted a lot of bugs before my users do (or at least before they decided to report it). I feel like it is much more important to contract test things that are likely to change rather than the file system for example
@spicynoodle7419
@spicynoodle7419 Жыл бұрын
@@alanonym8972 you should use something like Sentry to report exceptions, no need to rely on users.
@rosuewalford7767
@rosuewalford7767 Жыл бұрын
If a method depends on a integration point, how do I unit test that method without mocking the integraton point. Especially if the test environment will not have access to it. How will I avoid those null references?
@fennecbesixdouze1794
@fennecbesixdouze1794 Жыл бұрын
This is not a great take. tl;dr version; Mocks are good. The way people abuse mocking libraries is bad. What Prime is recommending "instead of mocking" is literally mocking. By the dictionary definition. And also by what you will be taught in any book about mocking, or from any of the people who developed these techniques. What we have here is what we pretty much always get in this industry: another programming cargo cult. People claiming to be using techniques they neither know nor understand, and the thing gets equated with whatever horrible nonsense people are doing just because they falsely claim to be doing the thing. A mock is supposed to be an input that you can run your code on which satisfies the interface you're programming to in a very simple/degenerate way. You absolutely should program to simple interfaces. That is the way to do testing and also to do design. The reason "mocking" sucks is because people have developed extensive "mocking libraries" which allow them to quickly and automatically produce objects that satisfy interfaces *without reducing the complexity of the thing being mocked*. The mocks have extensive, complicated behavior that makes the tests hard to reason about. Because the programmers don't redesign their code to simple and elegant interfaces, they instead leave the code complex and reach for some giant mocking tool so they can carefully orchestrate their rube-goldberg test. Whether he realizes it or would use the same terms or not, what Prime was recommending about separating the fiddling bit from the bit that fetches the stuff to fiddle *is in fact the essence* of unit testing and mocks in the actual definition of these terms. He's saying instead of writing input to the whole program, like a filename or an id for a row in a database, instead you put an interface between the fetching and the fiddling, and then you test the fiddling code with *a test thing substituted in for what in production will be coming out of the database*. Since "a-test-thing-substituted-in-for-what-in-production-will-be-coming-out-of-the-database" is very long and cumbersome to say, we introduce the word "mock" and define it to refer to the things you fiddle on in tests. Mocks are good. Mocking libraries are bad. If you have to reach to a mocking library to write a test, simplify your interfaces so you can write the mock by hand simply.
@lllXchrisXlll
@lllXchrisXlll Жыл бұрын
100% agree with you. On this one I very much disagree with Prime's take.
@asdq123456789
@asdq123456789 Жыл бұрын
Was a long scroll to find exactly what I was thinking. Nowhere in the video was mocking proven to be bad. Instead I saw a weird tangent about how people don’t understand features. The SQLite example is an advanced form of mocking in my mind. Taking some library that bruteforces a mock is ridiculous, people do that..?
@LordOfElm
@LordOfElm Жыл бұрын
In agreement on mocks. However, my employer requires us to have 80% "code coverage". It does not matter to them that it's type strict and compiled. Since the "fiddly" bits are not 80% of the code base, I am either forced to mock, or add a file with an unused function that does nothing but exceeds the length of the rest of the project so I can fulfill an arbitrary metric for management. I am also in the camp of "unit tests are also still code, equally prone to errors, and often more lines than the actual code they are testing".
@ThePrimeTimeagen
@ThePrimeTimeagen Жыл бұрын
this second idea is really good idea
@gentooman
@gentooman Жыл бұрын
>It does not matter to them that it's type strict and compiled Well obviously, why would it? Just cuz the app is type-safe doesn't mean it's behaving correctly. By that logic, all apps written in java are bug-free : )
@LordOfElm
@LordOfElm Жыл бұрын
@gentooman When your objective is "code coverage" then behavior validation and logic error checks need not apply. If it compiles we know it is free of syntax errors, which with the exception of some logic errors means that the code would execute. You might inadvertently find logic or behavioral errors in the process of achieving higher code coverage, but that's no guarantee. I'm not against unit testing, but I think they offer significantly less value for compiled type strict languages. Tests are also code, and if you mess up the implementation you can't expect your behavior checking code is somehow less error-prone. Even when checking inputs and outputs there are logic errors you may not catch.
@gentooman
@gentooman Жыл бұрын
​@@LordOfElm You sound just like every other junior developer who hates writing tests.
@NathanHedglin
@NathanHedglin Жыл бұрын
​@@gentoomanI'm an architect and tests are usually a net negative. Especially if one is chasing arbitrary code coverage. Why don't you test your unit tests? 😂
@NilMNV
@NilMNV Жыл бұрын
The main problem is that people just don't realise what exactly they can test with different kinds of tests. It's damn useful to have unit tests on sql queries using mocks (sql.Mock) to test marshalling and unmarshalling of structures, to test passing parameters in queries. It's just hilarious how many silly bugs, panics, etc. there can be at these levels. But that only tells you that the data flow in your code seems to be correct. Apply encapsulation and be fine.
@petedisalvo
@petedisalvo Жыл бұрын
The lesson here is not that mocking is bad. The lesson is don't mix high level policy code with infrastructure code. High level policy code pairs well with unit testing, dependency inversion, and fakes of various kinds, including mocks when appropriate. Infrastructure code pairs well with integration testing and using real, as close to production as possible, collaborators.
@AScribblingTurtle
@AScribblingTurtle Жыл бұрын
Someone claiming to have "fixed" how any language does its error handling is hilarious. The hoops some people invent and then jump through just so they can use something they are more familiar with never fails to amaze. I had to work with Mocha/Javascript Unit Tests ones and they connected to and manipulated a MongoDB. The DB Setup and -Cleanup after every test made at least 75% of the test code. It would have been a lot faster to just set up a local docker container and do a quick reset before each test run (it's like 2 bash commands to do so). But nooooo, none of the other devs knew how to use docker, so it was not allowed.
@ThePrimeTimeagen
@ThePrimeTimeagen Жыл бұрын
yikes this is why i love sqlite, you can use a file for testing which means that you can just cp a test file which has the perfect database setup and use that for integration / e2e tests. that is my fav :)
@saburex2
@saburex2 Жыл бұрын
Have you juniors heard of in memory db?
@scottwalker4619
@scottwalker4619 10 ай бұрын
How would this work for something like C# or Java? Traditionally, the Unit tests go in a separate project than the application code which means you can’t just split out functions and test them individually without first making those functions public? And making them when there’s no need for them to be public breaks best practices.
@anonimowelwiatko4455
@anonimowelwiatko4455 Жыл бұрын
In company I used to work, we tested for everything, even logs. Currently we only test functionality that means something, has purpose and needs to return/receive/modify values in certain way. Now I am not sure if author is talking about mocks. Mock is there to remove need for dependency in classes that have it while still preserving what function inside it will do (you can write whatever you want as functionality that mocked class does). In a way, you can write a mock that will behave exactly the same as class that you obviously wrote unit tests for and know that it work properly. Of course testing code in natural environment, some integration or interactive tests can be done on top of that but I usually find mocks and unit tests combined with CI Pipeline good enough and not face unforeseen issues (if tests and mocks were written correctly). You should always do stuff like stress tests etc. if your application needs to handle certain traffic as well and prepare for it beforehand.
@Tidbit0123
@Tidbit0123 10 ай бұрын
What if the unit tests del and create a database? Am I sunsetting?
@twihc294
@twihc294 Жыл бұрын
Eventually saveUserInDb and ValidateUser will be called in the top level function SaveUser How am I supposed to test SaveUser function without mocking? Or do I not test SaveUser function
@ScottLovenberg
@ScottLovenberg Жыл бұрын
Round trip saving, loading a user and removing a user. Then you know it actually works for the full life cycle.
@jimboxx7
@jimboxx7 Жыл бұрын
Why do you need to test SaveUser if all it's doing is calling your functions that are already tested? some code is not worth testing when it's too simple.
@ParabolJonas
@ParabolJonas Жыл бұрын
@@jimboxx7 To guarantee that SaveUser does what it's supposed to, I guess. Most of the time I'm not writing tests to ensure that my code works when writing it, but making sure that it keeps working after changing it. Let's say we stop calling saveUserInDb in the SaveUser function for some reason (maybe accidentally) and then we run the tests and see that they all pass.. yay?
@andreffrosa
@andreffrosa Жыл бұрын
Its useful to separate the logic part from the db part. Usually, that is done with Service classes and DAO classes. Then, you just test the Services and mock the DAOs. In this case, you would mock the saveInDB and test the SaveUser, with validateUser being a private auxiliary function that does not need to be tested independently.
@DontThinkSo11
@DontThinkSo11 Жыл бұрын
​​@@ParabolJonashe purpose of testing isn't to pour a layer of concrete over your code and make sure the behavior is locked in place. The purpose is to detect bugs. If you stopped calling SaveUserInDb in your higher level function, it's probably because you actually don't want to do that anymore. Your higher level function should include no logic of its own, so it should only stop doing that if you deleted the function call. If you really did accidentally delete it, then it will still get caught eventually in integration testing. There's no such thing as a testing framework that catches all bugs, so you should weigh the heaviness of your testing solution against the value of the types of bugs you expect it to catch.
@karolbielen2090
@karolbielen2090 5 ай бұрын
Does it only apply to backend development? What about frontend?
@albucc
@albucc Жыл бұрын
I find the "abuse" of mocks an issue. But I do see scenarios where you simply don't have the real thing to test or you do have an unstable environment with no valid test cases for you to check contour scenarios. I was one of the guys who worked with a code coverage target. At a project I even got at 100% code coverage. I still look at code coverage, to see "hey, there is this scenario that we totally did miss in our tests". And there are situations when what we need is a failure. Which in some situations may be difficult to test. Such as if the code itself is a wrapper around a real database that is supposed to handle different database responses, or a production webservice that we cannot really mess with or the customer doesn't have a stable uat environment, or we lack access to that environment at some point. In that case, either we create a mock server. Or stop development totally. At this moment mocks comes in handy. IN the video itself, there is a mention on "using an SQLLite" database. Is it the real production database? No, right? I do consider that a mock. I work with developing a framework that other people uses to make real life integrations. I don't have nor want access to the customer database or services, nor do I want to test them. But I do want to receive a json payload or an invalid json payload os some times sobre issues with payload content to test how my framework reacts to that situation. For these there is no way around: I need a mock server. In short: I think mocks have a niche use. At least at some steps of development.
@albucc
@albucc Жыл бұрын
@@d_6963 Exactly, when the feature to be tested is just how to handle a database response from a customer who has that mainframe based oracle database and is paying millions for it, and has personal sensitive data inside it, we can't just say, "Hey, I need to introduce a shortage in that database of yours, so I can make a test. Short thing, like we need a downtime of like , 2 minutes, some 20 times per day. Is that ok?" 😁
@HrHaakon
@HrHaakon Жыл бұрын
You could argue the stub vs mock difference, but I think that would be splitting hairs. I agree though, that most of the hate for things comes from weird management rules.
@retagainez
@retagainez 8 ай бұрын
@@HrHaakon I think it's just a bunch of misnomers, but if you describe the behavior of the test double, the context makes it easy to find out whether it's a stub or a fully fledged mock object.
@Optable
@Optable Жыл бұрын
Beeceptor has been a heavensend for mocking, debugging endpoints and timeout problems, testing adjustments pre/post production, CORS support, Customized Dynamic responses, Mock serving for OAS Specs. It's fantastic
@remrevo3944
@remrevo3944 Жыл бұрын
I would say there is one case where mocking is both trivial and definitely should be done: In Rust when parsing messages from some kind of data stream, when it is written correctly, it is easy to just get the test data and put it into a Cursor. That way you can just unit test the logic without having to do anything complicated.
@im-luke
@im-luke Жыл бұрын
I don't see any problem with using a mock in the described example. Everytime you use mock in your test, you just must be aware that the mocked part ALWAYS has to be tested in separate test. When you use mock or design your code the way it doesn't require using mock (e.g extract the problematic part from the code as it was proposed in the example), , in both situations you are avoiding using this probematicaly part of the code in your test, so the outcome is the same and what solution you choose doesn't really matter. I advocate the solution that you should ditinguish the "impure code" (= connection with external systems) from the "pure code" (testable, eg. data transform functions) but in some situations (e.g in OOP) you just need mocks.
@valkhorn
@valkhorn Жыл бұрын
Oh and I would also add that many devs do not know how to responsibly write INT tests. A good integration test should leave no trace or at least try to leave no trace it was there, and not cost you tons of money by connection to a third party API or hammering a database when you don’t need to. Unit tests at the base of the pyramid help to ensure the integration tests on top are minimized and are as least intrusive as possible. Or am I crazy in thinking you can have unit tests and int tests and no mocks and mocks and be perfectly fine?
@ozteched3838
@ozteched3838 7 ай бұрын
I love mocks in unit testing. if you use it properly you can test how your code should behave when different values are returned from mocked dependencies.
@comodsuda
@comodsuda Жыл бұрын
i like to write in-memory repositories to "mock" the database, but actually i;m using them on "prod" when it's only a prototype as well. The key idea is that i can run bazillion of test within a second or three but if i want to test it with real database - also no problem, just it's taking a little bit longer. For APIs my team also wrote inmemory service to pretend it's a real service. Usually these in-memory things are enough but several times real database and real api discovered some bugs. We're running all of the tests with real things before merging to master, but these in memory are used in development and they giving us instant feedback. That's the compromise i believe.
@pranavrajveer3767
@pranavrajveer3767 Жыл бұрын
00:00 - Introduction 00:09 - Know Your Language 00:21 - Mocks and Dependency Injection 00:31 - The Problem with Mocks 00:48 - The Story of Bill 01:34 - The Virtues of Errors as Values 02:04 - Unit Testing Database Logic 03:37 - Integration Tests vs. Unit Tests 07:03 - The Code is Ass 08:10 - Stop Mocking 10:45 - Separating Logic and Testing 11:17 - Conclusion
@Veptis
@Veptis 7 ай бұрын
My PR is done. But now I need to add unit tests. So the motivation hits hard
@Cowboydjrobot
@Cowboydjrobot 3 ай бұрын
I’m always trying to explain this to junior guys. “We don’t need to tea the c++ stl. You only need to be testing your logic.”
@爱学习-s6k
@爱学习-s6k Жыл бұрын
So basically you test your database access function, read or write. Connected to a real database, and do the Integration testing. Then modularize those fiddling functions, possibly pure so unit testing is easy. Then you have an Integration testing again with database for the entire api endpoints? Is that how you backend engineets usually test backend API? Just curious🧐
@r2-p2
@r2-p2 Жыл бұрын
How do you test a class (having internal state) with dependencies without mocking the dependencies?
@AzureFlash
@AzureFlash Жыл бұрын
Title: "Thoughts About Unit Testing" Thumbnail: "Stop doing this" You got it boss, no more unit testing for me!
@Thorarin
@Thorarin 7 ай бұрын
Mocks are tricky for sure. Just a few days ago I ran into a set of tests that so much mocking going on, I couldn't figure out if there was any production code left that was effectively tested. Despite all that, I still think they have many uses. You just need to know when to stop.
@ClintonChelak
@ClintonChelak Жыл бұрын
8:00 The sound of silence can be pretty intense, though notably he changed to more silence.
@melodyogonna
@melodyogonna Жыл бұрын
You still didn't explain why mocks should not be used. Mocks effectively ensure that only the fiddling part is tested as well, but without having to move functions around.
@DudeWatIsThis
@DudeWatIsThis 11 ай бұрын
6:36 Wait- does ANYONE do it any other way after their first year in college?
@emjizone
@emjizone Жыл бұрын
Are mocks a way for devs to make things fail in spite they failed to introduce bugs in the test functions ?
@alienrenders
@alienrenders 11 ай бұрын
Apologies for the late reply. Thought this was an interesting question. Generally yes, you can make it fail in situations where the real implementation(s) would be difficult to induce a failure. But it's also a way to control or force behavior on an object. Basically a mannequin. Then you can test the thing that interacts with it. There's also another use case is where you want to ensure that a specific piece of code behaves a certain way. For example, you want to ensure that the code calls a method that verifies a password. You would do something like EXPECT_CALL(mock, VerifyPassword(_).Times(1)) in C++ with gmock or whatever the syntax is. You can tell it what to return, and even check what the argument is supposed to be. Here, we tell it we expect VerifyPassword to be called exactly 1 time. If it is called 0 times or 2 times or more, the test fails. You can set many such expectations. I'm not as against mocking as the channel owner is. I find it's most useful on parts that interact with a lot of things and is very hard to test. So you get some mocks and then you can test the main code. That's where I think mocking is useful. It lets you test code that otherwise would be very difficult or impossible to do otherwise. It also allows you to write unit tests before a specific module or set of functionality is completed. The downside is that it's very time consuming to set up the mock object and set up proper expectations. It's also very intrusive on testing the implementation of the code instead of its results. If you're testing how something is implemented, you're probable going down the wrong road. And that's a big part of what mocking does and why a lot of people hate it.
@DNHRobot
@DNHRobot 9 ай бұрын
I feel like people misunderstood the point of unit test. It's not suppose to test the real world use case it's a sanity for your small unit of code. Should be small and quick to execute and to catch unexpected edge case or when the 'unit' is somehow modified later on. It's only like the first step of testing
@jimiscott
@jimiscott Жыл бұрын
I am beginning to wonder if Prime's self professed knowledge of development is actually pretty narrow. If throwing around blanket statements like 'never mocking' then perhaps you've worked on simple systems that never require mocks in the first place?
@sismith5427
@sismith5427 10 ай бұрын
You mean like that super simple codebase called Netflix... they only have a few hundred users I heard, that's not a complex codebase at all....
@allalphazerobeta8643
@allalphazerobeta8643 Жыл бұрын
One thing not mentioned is the "intergrated function" returned both an error for bad user/passwords and for database problems in the same variable... This is criminal but also the kind of code a try: catch: pattern encourages. Think about what the code looks like to handle the error of this function: (lifted from the article.) func saveUser(db *sql.DB, user User) error { if user.EmailAddress == "" { return errors.New("user requires an email") } if len(user.Password) < 8 { return errors.New("user password requires at least 8 characters") } hashedPassword, err = hash(user.Password) if err != nil { return err } _, err := db.Exec(` INSERT INTO users (password, email_address, created) VALUES ($1, $2, $3);`, hashedPassword, user.EmailAddress, time.Now(), ) return err }
@MikeZadik
@MikeZadik Жыл бұрын
How do I test the unit that calls saveUserInDB if validateUser was successful? At some point i need to moq those external resources.
@Nellak2011
@Nellak2011 Ай бұрын
I will say that using property tests is far less code than manual unit tests and it is general enough to cover unit tests to mocks. The only time example based makes sense is end-to-end or if you have specific cases that need to be checked that are extremely hard to reach randomly. If you are still a JS dev check out fast-check.
@briankarcher8338
@briankarcher8338 Жыл бұрын
I sometimes need to unit test my sql and Testcontainers is an excellent option to do that. Plus, mocking external dependencies is important. Example: Calls into your cloud provider. Mocking AWS SQS and asserting the data sent to it is extremely important. Internal dependencies? You need to have a good reason to have an interface and mock for an internal dependency. A real good reason because you usually won't find that reason. Mocking internal code usually just reduces your code coverage and forces you to write more tests. Why?
@AndrewErwin73
@AndrewErwin73 Жыл бұрын
god to the jr... media personality to the sr.
@TheJobCompany
@TheJobCompany Жыл бұрын
I didn't think code coverage is problematic until I ran into a very pleasant and necessary test in a Django project.. basically the framework has a reverse() function, which takes the name of a view and returns its url, as configured in the routing layer, and a resolve() function, which does exactly the opposite of that. The unit test was taking 3 screens "testing the urls", ensuring that resolve(reverse(x)) == x. I'm so glad the url configuration had 100% coverage, I don't know how I would've rested if that test wasn't present in it.
@SemiMono
@SemiMono Жыл бұрын
9:08 you should not write mundane tests. Arguably you shouldn't write out simple data validation, but instead use some kind of schema validator akin to json schema or protobuf (yeah, protobuf is secondarily a schema validator). Perhaps the example was made simple for ease of reading, fine, but I have seen a lot of code written like that and I would maintain that if it's as simple as what's there, it should not have dedicated tests. On the other hand, I completely agree with how bad mocks are. I absolutely agree integration tests are very useful.
@bennguyen1313
@bennguyen1313 10 ай бұрын
Any idea how Comma AI does its (regression) testing? I assume they use an open-source tool (CppUTest, google test , catch2, doctest) but what?
@morgengabe1
@morgengabe1 Жыл бұрын
Imo, test writing is a team leader/project manager's job. Replace design briefs with actual specifications by limiting well designed tests. Would make it a lot easier to teach Juniors too.
@jf3518
@jf3518 Жыл бұрын
I love external service mocks in integration testing. I am using boto, localstack and docker compose to mock databases and aws service apis. This way I can develop a lambda function, ecs service or whatever locally and directly integrate it with surrounding services with the iteration time of a few seconds. It is awesome as it speeds up development significantly, makes me confident that the code and infrastructure code will run fine in cloud environments (yes you can run terraform or aws cdk against it too) and it is a clear working documentation of the API and how other services interact with it. It can even be used to test IAM policies locally without a single deploy to AWS!!!!!1111
@tdiblik
@tdiblik Жыл бұрын
Putting code that fetches data into separated function is a double edges sword, because some people don't care about the underlying code, so instead of writing their own sql query that does join, they instead use your "abstraction functions" and overfetch data af. Personally, I prefer always fetching at the function that handles the api request. All other functions that fiddle with data can be on their own, but once I'm passing db connection to a function, something, somwhere went terribly wrong xd
@Comeyd
@Comeyd Жыл бұрын
And that’s why you don’t “over expose” your functions. The only functions callable should be the functions that operate exactly as intended. i.e. don’t make every function public. It’s okay to have your logical bits separated, and then create a public function that chains them together in the correct order. This documents how it is supposed to be used, and prevents misuse.
@Zuftware
@Zuftware Жыл бұрын
Why you all imply that starting local postgres instance is something hard or slow or bad in some other way?
@goffkock
@goffkock Жыл бұрын
Didn’t the run an actual Postgres instance? Then it’s no mock!
@nZifnab
@nZifnab Жыл бұрын
At my job, we work mainly in Rails... our biggest mantra is, "if you find yourself fighting rails, you're probably doing something wrong".... this is what I think of when I see someone circumventing a Go feature to add.... a tryCatch function? That just sounds awful.
@oefzdegoeggl
@oefzdegoeggl 2 ай бұрын
Depends on how much actual logic you have in there. In the case of a HTTP backend with a database, I usually skip the unittests altogether and test externally against the API. Which drops the need for logic separation. The main problem here is usually that you have external side effects which require context knowledge that you (should) not have in a unittest. It's just not worth writing actual testable code if the unittest will cover 5% of the possible errors and you have to write an external test anyways, which when run against the API can also test correct parameter processing, correct return values setup, correct permission checks and possible side effects (e.g. missing WHERE clause in a DELETE statement). When actually mocking, then do it right, means: The mock must mimic the behaviour towards the caller exactly like the original object does. But in general I agree with you, avoid mocks when possible, they can be tricky to get right.
@michaelharrington6698
@michaelharrington6698 Жыл бұрын
Prefer (in memory) fakes over mocks anyday. You should invest in a db fake and then you can test the write and read (100 percent of the backend) in unit tests like this: write op 1, write op 2, write op 3, read op 1 assert output. Of course in addition to the advice peddled here to break out the fiddling into isolated functions to test.
@StevenHunt1
@StevenHunt1 11 ай бұрын
I've run "unit tests" with in memory sqlite, it was super fast and easy and with much of the logic being in the SQL queries it added a lot of value.
@TurtleKwitty
@TurtleKwitty Жыл бұрын
My last job had some points where things were injected 36 layers down and every layer wanted a test with mock injections no matterh ow useless the test was it was baddddd
@purocharly
@purocharly Жыл бұрын
LOL
@morosis82
@morosis82 6 ай бұрын
In general I agree, but unfortunately using sqlite as a backend for tests just doesn't always work. Have had a few runins with it just not supporting some fairly basic functions that are in Postgres, so there's no way to make that integration test pass with sqlite.
@venir_dev
@venir_dev Жыл бұрын
So, in a nutshell: write stubs, not mocks..?
Lets Chat About Unit Tests
15:06
ThePrimeTime
Рет қаралды 102 М.
How to -10x Engineer Correctly
22:22
ThePrimeTime
Рет қаралды 529 М.
Леон киллер и Оля Полякова 😹
00:42
Канал Смеха
Рет қаралды 4,7 МЛН
Мясо вегана? 🧐 @Whatthefshow
01:01
История одного вокалиста
Рет қаралды 7 МЛН
99.9% IMPOSSIBLE
00:24
STORROR
Рет қаралды 31 МЛН
DONT USE AN ORM | Prime Reacts
25:46
ThePrimeTime
Рет қаралды 246 М.
How Senior Programmers ACTUALLY Write Code
13:37
Thriving Technologist
Рет қаралды 1,6 МЛН
The purest coding style, where bugs are near impossible
10:25
Coderized
Рет қаралды 1 МЛН
You're Not Qualified To Have An Opinion On TDD | Prime Reacts
13:37
I Went To DEFCON!
16:25
ThePrimeagen
Рет қаралды 342 М.
My 10 “Clean” Code Principles (Start These Now)
15:12
Conner Ardman
Рет қаралды 316 М.
Why I Don’t Unit Test
8:25
Theo - t3․gg
Рет қаралды 92 М.
When To Unit, E2E, And Integration Test
14:58
ThePrimeTime
Рет қаралды 106 М.
Devops is Terrible
24:36
ThePrimeTime
Рет қаралды 322 М.
Dependency Injection, The Best Pattern
13:16
CodeAesthetic
Рет қаралды 909 М.
Леон киллер и Оля Полякова 😹
00:42
Канал Смеха
Рет қаралды 4,7 МЛН