Thoughts About Unit Testing | Prime Reacts

  Рет қаралды 200,453

ThePrimeTime

ThePrimeTime

9 ай бұрын

Recorded live on twitch, GET IN
/ theprimeagen
Article: blog.boot.dev/clean-code/writ...
Author: Lane Wagner - / bootdotdev
support me by checking out: boot.dev/
MY MAIN YT CHANNEL: Has well edited engineering videos
/ theprimeagen
Discord
/ discord
Have something for me to read or react to?: / theprimeagenreact

Пікірлер: 464
@tiskahar9738
@tiskahar9738 9 ай бұрын
the irony of listening to this while actively writing mocks and excessively unit testing
@Kalasklister1337
@Kalasklister1337 9 ай бұрын
just today i wrote a single test with three mocks in it...
@SaHaRaSquad
@SaHaRaSquad 9 ай бұрын
The things we do to try staying sane.
@liquidsnake6879
@liquidsnake6879 9 ай бұрын
@@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 9 ай бұрын
When I write mocks, I do it in Rust.
@TheStickofWar
@TheStickofWar 9 ай бұрын
@@liquidsnake6879yeah there is no problem with it, people should remember that here isn’t the word of god
@pdwarnes
@pdwarnes 9 ай бұрын
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 9 ай бұрын
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 9 ай бұрын
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 9 ай бұрын
@@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 9 ай бұрын
@@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 9 ай бұрын
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
@bobbycrosby9765
@bobbycrosby9765 9 ай бұрын
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 8 ай бұрын
That’s a good point
@Adowrath
@Adowrath 7 ай бұрын
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).
@user-dq7vo6dy7g
@user-dq7vo6dy7g 7 ай бұрын
yeah well. Just put a list of all users in as parameter. There problem solved. Skill issue /s
@stevemartin2981
@stevemartin2981 7 ай бұрын
Use factories? No db needed and much faster
@Adowrath
@Adowrath 7 ай бұрын
​@@stevemartin2981How would a Factory help with validation that depends on context stored in the database?
@PhillipDressen
@PhillipDressen 9 ай бұрын
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 6 ай бұрын
Right? I absolutely agree it would be awesome to use the same language throughout the stack... but who thought JAVASCRIPT should be that language???
@AJMansfield1
@AJMansfield1 9 ай бұрын
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 4 ай бұрын
I know you said dynamic languages, but this all seems like non-problems that the compiler should enforce
@jeromesnail
@jeromesnail 7 ай бұрын
Great advice if all your functions are independent. It might be the case of 1% of all written code.
@shanebenning
@shanebenning 9 ай бұрын
“… fixed TypeScript’s biggest problem” is the summoning ritual for Matt
@tech3425
@tech3425 9 ай бұрын
Exactly what i thought 😂 If you say you've fixed a language's biggest problem...then you're Matt Pocock
@DrPizza92
@DrPizza92 9 ай бұрын
What’s up wizards?
@kaanatakan
@kaanatakan 9 ай бұрын
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 9 ай бұрын
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 9 ай бұрын
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 9 ай бұрын
@@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 9 ай бұрын
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 4 ай бұрын
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.
@noherczeg
@noherczeg 9 ай бұрын
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 9 ай бұрын
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.)
@kairo1502
@kairo1502 9 ай бұрын
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 9 ай бұрын
Thank you!
@VideoWow7184
@VideoWow7184 8 ай бұрын
Yep, read that one, it's really good.
@darkdreamflyer2317
@darkdreamflyer2317 8 ай бұрын
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)
@asdfasdf9477
@asdfasdf9477 9 ай бұрын
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.
@pycz
@pycz 9 ай бұрын
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 9 ай бұрын
@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 9 ай бұрын
@@jarosawsmiejczak1138 Rails takes a similar approach iirc
@smallfox8623
@smallfox8623 9 ай бұрын
testcontainers is great for this case
@QckSGaming
@QckSGaming 9 ай бұрын
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 9 ай бұрын
⁠@@QckSGamingI realize in recent years that most people in this industry don't even understand the basic difference between unit test and integration test.
@moraigna66
@moraigna66 9 ай бұрын
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 9 ай бұрын
Yep - Fine with mocks - particularly on complex systems - yes they can get complex.
@Qrzychu92
@Qrzychu92 9 ай бұрын
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 9 ай бұрын
@@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 9 ай бұрын
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 8 ай бұрын
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.
@fennecbesixdouze1794
@fennecbesixdouze1794 9 ай бұрын
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 9 ай бұрын
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
@remrevo3944
@remrevo3944 9 ай бұрын
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.
@drknoba
@drknoba 9 ай бұрын
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 5 ай бұрын
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
@EbonySeraphim
@EbonySeraphim 8 ай бұрын
This absolutely 👏🏿👏🏿👏🏿 As soon as I learned about mocks, I intuitively thought something was off about them. I came to see limited value due to the use of a very difficult coding framework (AWS SWF’s Flow Framework), but outside of that I saw a bunch of devs pretend that they needed to test that database and other remote call parameters were set exactly. If anything necessarily changed with the API functionally the same, you broke the test for sure because it was validating the internal procedure not the behavior. The most substantial benefit I see to mocks is when you need to test exception handling behavior. With a real database or remote connection, testing against unstable or failed network conditions is too annoying to simulate. You can have a remote call trigger an exception a number of times before returning to verify that internal retries are happening too.
@theherk
@theherk 9 ай бұрын
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.
@misskalkuliert3976
@misskalkuliert3976 6 ай бұрын
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 4 ай бұрын
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...
@user-yn8gk5gx5w
@user-yn8gk5gx5w 9 ай бұрын
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 9 ай бұрын
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 9 ай бұрын
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 9 ай бұрын
@@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 9 ай бұрын
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 4 ай бұрын
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.
@TeaBroski
@TeaBroski 4 ай бұрын
you gotta appreciate the Ryan George "super easy, barely an inconvenient" quote
@krccmsitp2884
@krccmsitp2884 7 ай бұрын
I love all of it, from the article and your reaction. 🙂
@alexaneals8194
@alexaneals8194 7 ай бұрын
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.
@se4geniuses
@se4geniuses 9 ай бұрын
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.
@axelfoley133
@axelfoley133 9 ай бұрын
4:05 One doesn't simply insert Screen Rant memes into dev content. Bootdev: Actually it's super easy. Barely an inconvenience.
@sutirk
@sutirk 9 ай бұрын
Im gonna need you to get alll the way off his back
@bootdotdev
@bootdotdev 9 ай бұрын
OH REALLY
@Evan-dh5oq
@Evan-dh5oq 9 ай бұрын
It's definitely tight
@axelfoley133
@axelfoley133 9 ай бұрын
@@sutirk ok well let me climb off that thing
@Patrick_Bard
@Patrick_Bard 9 ай бұрын
yeah yeah yeah
@ripple123
@ripple123 9 ай бұрын
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 9 ай бұрын
till you have one or two errors. When you have to handle 5+ probable errors your code becomes ugly.
@AJ213Probably
@AJ213Probably 9 ай бұрын
@@banatibor83 but is it better trying to handle 5+ probable errors that you don't know?
@anonimowelwiatko4455
@anonimowelwiatko4455 7 ай бұрын
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.
@bootdotdev
@bootdotdev 9 ай бұрын
LOVE TO SEE IT. Thanks for the read Prime
@SkillTrailMalefiahs
@SkillTrailMalefiahs 9 ай бұрын
You have excellent articles bro!! :D
@bootdotdev
@bootdotdev 9 ай бұрын
@@SkillTrailMalefiahs yoooo thanks
@jf3518
@jf3518 7 ай бұрын
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
@kezzu5849
@kezzu5849 9 ай бұрын
Shout out to the author for using "Super easy, barely an inconvenience" 😂 Pitch Meeting has reached the far reaches of the internet 🙏🏿
@TheJobCompany
@TheJobCompany 9 ай бұрын
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.
@ScottLovenberg
@ScottLovenberg 9 ай бұрын
Yo dawg, we heard you like mocks....
@Thomas_Lo
@Thomas_Lo 9 ай бұрын
...so we mocked your mocks.
@spl420
@spl420 9 ай бұрын
​@@Thomas_Loso you can mock your mocks while you are mocking your mocks.
@spicynoodle7419
@spicynoodle7419 9 ай бұрын
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 9 ай бұрын
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 9 ай бұрын
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 9 ай бұрын
@@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 9 ай бұрын
@@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 9 ай бұрын
@@alanonym8972 you should use something like Sentry to report exceptions, no need to rely on users.
@ClaytonHarbich
@ClaytonHarbich 4 ай бұрын
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?
@wbtittle
@wbtittle 6 ай бұрын
God Bless You.
@KlemensSoftware
@KlemensSoftware 5 ай бұрын
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 2 ай бұрын
Docker solves this. Most languages have some integration with test containers, if not, it’s straightforward to roll your own.
@rosuewalford7767
@rosuewalford7767 7 ай бұрын
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?
@LEGnewTube
@LEGnewTube 9 ай бұрын
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 9 ай бұрын
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 9 ай бұрын
@@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 9 ай бұрын
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 9 ай бұрын
A more accurate statement would be you shouldn’t mock in unit tests
@LEGnewTube
@LEGnewTube 9 ай бұрын
@@ashvinnihalani8821 Sure, but if you need to test the whole flow of the main function than you would need to use a mock.
@StevenHunt1
@StevenHunt1 3 ай бұрын
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.
@petedisalvo
@petedisalvo 4 ай бұрын
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.
@LordOfElm
@LordOfElm 9 ай бұрын
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 9 ай бұрын
this second idea is really good idea
@gentooman
@gentooman 9 ай бұрын
>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 9 ай бұрын
@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 9 ай бұрын
​@@LordOfElm You sound just like every other junior developer who hates writing tests.
@NathanHedglin
@NathanHedglin 9 ай бұрын
​@@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? 😂
@user-dq7vo6dy7g
@user-dq7vo6dy7g 7 ай бұрын
How do I test the unit that calls saveUserInDB if validateUser was successful? At some point i need to moq those external resources.
@teaman7v
@teaman7v 9 ай бұрын
Great article
@vytah
@vytah 9 ай бұрын
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.
@comodsuda
@comodsuda 4 ай бұрын
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.
@zevo92
@zevo92 9 ай бұрын
1:36 minutes into the video, am already very much entertained. I love this man :X (Disclaimer: In a very platonic way)
@BorisTheDev
@BorisTheDev 9 ай бұрын
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.
@pranavrajveer3767
@pranavrajveer3767 7 ай бұрын
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
@michaelharrington6698
@michaelharrington6698 8 ай бұрын
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.
@bscharbau
@bscharbau 9 ай бұрын
How do you now test that the validation is actually performed before saving anything to the database without using a real database or mocks?
@albucc
@albucc 9 ай бұрын
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 9 ай бұрын
@@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 9 ай бұрын
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.
@khatdubell
@khatdubell 9 ай бұрын
Depends on what you're mocking, and how. I frequently mock network components
@morgengabe1
@morgengabe1 9 ай бұрын
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.
@NilMNV
@NilMNV 9 ай бұрын
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.
@vincenthamel3420
@vincenthamel3420 3 ай бұрын
We once had a devastating bug in production. And management was dumbfounded as to how it could happen as we had a near perfect code coverage in that servlet. ... Open up the tests for said servlet, meet a huge block of mocks at the beginning of every test. Proceed to inform our manglement that we don't actually have any test, just a whole bunch of mocks. Manglement did not like me pointing out problems, and we still have mocks.
@autohmae
@autohmae 4 ай бұрын
8:44 don't specifically need ORM, just an encapsulation function to not do it raw. A function which generates the SQL.
@briankarcher8338
@briankarcher8338 4 ай бұрын
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?
@ivanovichru510
@ivanovichru510 9 ай бұрын
Love the Ryan George "Super easy, barely an inconvenience".
@Aralmo640
@Aralmo640 6 ай бұрын
Mocks are the part of that fiddling function you don't test, usually that function is not just a map, it would have some logic, need to fetch data from a dependency only in specific cases and stuff like that. You can solve it by having function composition or delegates too, but in the world of dependency injection we live in I believe mocks are prety usefull. Why would you test again a dependency that is already tested? Why would you take the burden of having to initialize everything that dependency needs in your test again? Just mock it and test the fiddling part, it's a couple lines of code versus many lines of initialization and the danger of having tests overlapping each other. When someone says that overused phrase "if you mock you are not testing anything" I always ask if they are doing functional programming or what kind of dependency inversion they are using, if they use dependency injection, that sentence makes no sense to me at all.
@Optable
@Optable 6 ай бұрын
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
@chiefxtrc
@chiefxtrc 9 ай бұрын
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 9 ай бұрын
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 9 ай бұрын
@@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.
@im-luke
@im-luke 5 ай бұрын
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.
@marcgentner1322
@marcgentner1322 9 ай бұрын
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?
@irreadings
@irreadings 8 ай бұрын
Oh man I laughed out loud at that hand on face joke. This doesn't happen where I live
@valcron-1000
@valcron-1000 9 ай бұрын
This approach is fine, until your pure logic _depends_ on data that comes from the DB. For example (In TS) function saveUser(user: User, db: Database) { let sameEmail = db.getUserByEmail(user.email) if (sameEmail) { throw new Error("Email already in use") } if (user.password.length < 8) { throw new Error("Password is too short"); } /* more validation */ db.saveUser(user) } When this happens, your unit tests end up reimplementing the code inside `saveUser`, creating a dependency to the implementation. If you can, you always want to write pure functions, but sometimes there are hard logic dependencies that you cannot just ignore, otherwise you end up coupled to the implementation. Using mocks, you can actually test the expected behavior without this coupling.
@valcron-1000
@valcron-1000 9 ай бұрын
Another situation (I've been there when writing Haskell) is that in order to keep the business logic pure, you end up defunctionalizing the codebase, separating what should be done from the actual execution. This makes things far more complicated (involves writing an interpreter, defining all possible actions in form of data types, etc) than just using mocks.
@LukeFrisken
@LukeFrisken 9 ай бұрын
@@valcron-1000 I agree, I've also been there, and it can make the code a lot more complicated sometimes than just using a mock.
@AScribblingTurtle
@AScribblingTurtle 9 ай бұрын
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 9 ай бұрын
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 :)
@adamstrejcovsky8257
@adamstrejcovsky8257 8 ай бұрын
The thing about mocks and unit tests, they look useless until you run them😂then you are happy you have wrote them
@allalphazerobeta8643
@allalphazerobeta8643 9 ай бұрын
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 }
@marcbotnope1728
@marcbotnope1728 9 ай бұрын
Check your unit tests privilege! Some of us are happy if there are any automated testst at all.
@askolotus_prime
@askolotus_prime 6 ай бұрын
:D
@valkhorn
@valkhorn 9 ай бұрын
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?
@tdiblik
@tdiblik 9 ай бұрын
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 7 ай бұрын
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.
@nryle
@nryle 4 ай бұрын
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.
@DNHRobot
@DNHRobot 26 күн бұрын
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
@stevemartin2981
@stevemartin2981 7 ай бұрын
I ❤❤ mocks personally. I am a mockist through and through. Factories make it so effective
@ariellecherieart
@ariellecherieart 22 күн бұрын
Can you elaborate about factories w mocks
@Milotiiic
@Milotiiic 5 ай бұрын
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
@SemiMono
@SemiMono 9 ай бұрын
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.
@hellowill
@hellowill 6 ай бұрын
Yeah basically most backend code is like this: Controller -> BusinessLogic (some people call this 'Service' just call it BusinessLogic ffs) -> Repository (Database or another API) You only unit test the BusinessLogic. Integration test can cover the entire path. But I still don't agree with "never mock". Tried it, and the codebase got so many bugs over time due to poor coverage.
@atiagosoares
@atiagosoares 8 ай бұрын
This video cured me of my dependency injection
@maxnibler6090
@maxnibler6090 6 ай бұрын
I'm brand new to go, learning it now thanks to Prime's videos. Hadn't heard of Naked returns yet. I googled it after he mentioned it because I couldn't tell what they were from that brief mention. I literally stood up in my chair when I read the documentation. I don't like that. I will not be using that feature lol
@klamberext
@klamberext 3 ай бұрын
In some cases i separatr the raw db stuff to a separate module. Repositories use it. And in case it's not just aplain insert/update and a more compõex aggregation query i add a test to it and add a env variable to stop this suite running in CI pipeline. I tend to forget and make stupid AdHD kind of mistakes so I at least can locally verify. And if its just for me I have a global git ignore pattern and I never commit my "sanity checks". But I do admit I have started to put more of my efforts into having a good separation between business and infra. Less tests and living with not having 99% coverage.
@ybcoding5153
@ybcoding5153 4 ай бұрын
I'll argue also that you need to verify everything (pure functions) is called and in the order you expect...because it is great to UT but it also great to check what you tested is actually used. So for this you need to mock your pure functions. In short, yes when you mock too much, something smells in your code.
@ClintonChelak
@ClintonChelak 9 ай бұрын
8:00 The sound of silence can be pretty intense, though notably he changed to more silence.
@peachezprogramming
@peachezprogramming 5 ай бұрын
as an aspiring backend dev, I am so happy i understand this
@johngagon
@johngagon 9 ай бұрын
the funkiest diddling I've heard in a long time.
@WindupTerminus
@WindupTerminus 9 ай бұрын
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 9 ай бұрын
hahahaha
@ThePrimeTimeagen
@ThePrimeTimeagen 9 ай бұрын
also sorry
@HrHaakon
@HrHaakon 9 ай бұрын
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 9 ай бұрын
@@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 9 ай бұрын
@@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.
@nZifnab
@nZifnab 6 ай бұрын
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.
@JefersonEuclides
@JefersonEuclides 9 ай бұрын
As a NodeJS developer, I'll say this: I laughed, a lot. Then cried, just a bit.
@elementotriplo4966
@elementotriplo4966 9 ай бұрын
I need to try doing this "never mocking" thing, generally i'm writing C# backend code, or Android with Kotlin for apps, and we mock the heck out of everything, wanna test this CreateRecipeUseCase? Uses error message internationalization, if so don't forget to mock StringLocalizer, oh but it also needs to know the user to check for access authorization? well then, mock the LoggedUserProvider, Oh and also the RecipeRepository so you don't access the database I forgot to tell you that you need to mock the UnitOfWork as well That is exactly how I code, but i don't know better, i should invest sometime refactoring my code to support the "never mocking" thingy
@eugenakv
@eugenakv 9 ай бұрын
No, you should not. Your tests are fine.
@r2-p2
@r2-p2 5 ай бұрын
How do you test a class (having internal state) with dependencies without mocking the dependencies?
@AzureFlash
@AzureFlash 9 ай бұрын
Title: "Thoughts About Unit Testing" Thumbnail: "Stop doing this" You got it boss, no more unit testing for me!
@SurfsUpSeth
@SurfsUpSeth 8 ай бұрын
This guy could be a voice actor for English dubbed anime’s
@mac1414
@mac1414 4 ай бұрын
Not unit testing the business logic is junior dev code. Doesn't matter if work for FAANG or not. You test the heart of your system, which is irreplacable, versus everything else which is replaceable (infra layers), which is tested by integration tests.
@NyaowYeon
@NyaowYeon 9 ай бұрын
Thanks
@ThePrimeTimeagen
@ThePrimeTimeagen 8 ай бұрын
WOAH!! a super. ty ty
@cubbucca
@cubbucca 9 ай бұрын
can someone explain at what point this stopped being mocked? or is having a mock db the issue? cause I thought &User{ deats } is also a mock.
@isaacyonemoto
@isaacyonemoto 9 ай бұрын
You gotta mock connecting to 3p SAASes, in integration tests.
@GnomeEU
@GnomeEU 9 ай бұрын
Lets mock this endpoint, it returns always true! > But my app only breaks when it doesn't return true or returns invalid data. We've finished our test, move along.
@skudge
@skudge 8 ай бұрын
last company i worked for refused to let use use an orm and we had to raw-dog sql everywhere
@tongobong1
@tongobong1 4 ай бұрын
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.
@jimiscott
@jimiscott 9 ай бұрын
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 2 ай бұрын
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....
@bobross6228
@bobross6228 9 ай бұрын
Scariest thing here was the naked squeal
When To Unit, E2E, And Integration Test
14:58
ThePrimeTime
Рет қаралды 83 М.
Have We Forgotten How To Program?? | Prime Reacts
22:53
ThePrimeTime
Рет қаралды 400 М.
LA FINE 😂😂😂 @arnaldomangini
00:26
Giuseppe Barbuto
Рет қаралды 21 МЛН
1 класс vs 11 класс (рисунок)
00:37
БЕРТ
Рет қаралды 4,1 МЛН
Cute ❤️🤣🍒 #shorts
00:15
Koray Zeynep
Рет қаралды 5 МЛН
Lets Chat About Unit Tests
15:06
ThePrimeTime
Рет қаралды 86 М.
"Clean" Code, Horrible Performance
22:41
Molly Rocket
Рет қаралды 826 М.
ThePrimeagen Hacks My Productivity
3:30
Scott Macchia
Рет қаралды 28 М.
Why Linus Torvalds Insults People | Prime Reacts
17:53
ThePrimeTime
Рет қаралды 303 М.
Devops is Terrible
24:36
ThePrimeTime
Рет қаралды 263 М.
Why I Don’t Unit Test
8:25
Theo - t3․gg
Рет қаралды 85 М.
Clean Code is SLOW But REQUIRED? | Prime Reacts
28:22
ThePrimeTime
Рет қаралды 253 М.
How Senior Programmers ACTUALLY Write Code
13:37
Healthy Software Developer
Рет қаралды 1,2 МЛН
Python Sucks And I LOVE It | Prime Reacts
15:43
ThePrimeTime
Рет қаралды 230 М.
3 Chars - 20x Perf Improvement
8:46
ThePrimeTime
Рет қаралды 47 М.
Я Создал Новый Айфон!
0:59
FLV
Рет қаралды 2,2 МЛН
Эволюция телефонов!
0:30
ТРЕНДИ ШОРТС
Рет қаралды 3,9 МЛН
Что еще за обходная зарядка?
0:30
Не шарю!
Рет қаралды 267 М.
Самый маленький игровой ПК
0:46
ITMania - Сборка ПК
Рет қаралды 590 М.