Thoughts About Unit Testing | Prime Reacts

Sdílet
Vložit
  • čas přidán 18. 07. 2023
  • 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
  • Věda a technologie

Komentáře • 471

  • @tiskahar9738
    @tiskahar9738 Před 10 měsíci +520

    the irony of listening to this while actively writing mocks and excessively unit testing

    • @Kalasklister1337
      @Kalasklister1337 Před 10 měsíci +31

      just today i wrote a single test with three mocks in it...

    • @SaHaRaSquad
      @SaHaRaSquad Před 10 měsíci +2

      The things we do to try staying sane.

    • @liquidsnake6879
      @liquidsnake6879 Před 10 měsíci +29

      @@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 Před 10 měsíci +1

      When I write mocks, I do it in Rust.

    • @TheStickofWar
      @TheStickofWar Před 10 měsíci +3

      @@liquidsnake6879yeah there is no problem with it, people should remember that here isn’t the word of god

  • @jeromesnail
    @jeromesnail Před 7 měsíci +13

    Great advice if all your functions are independent. It might be the case of 1% of all written code.

  • @pdwarnes
    @pdwarnes Před 10 měsíci +204

    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 Před 10 měsíci +20

      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 Před 10 měsíci +4

      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 Před 10 měsíci +8

      @@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 Před 10 měsíci

      @@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 Před 10 měsíci +5

      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 Před 10 měsíci +76

    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 Před 9 měsíci +4

      That’s a good point

    • @Adowrath
      @Adowrath Před 8 měsíci +12

      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 Před 8 měsíci +4

      yeah well. Just put a list of all users in as parameter. There problem solved. Skill issue
      /s

    • @stevemartin2981
      @stevemartin2981 Před 7 měsíci

      Use factories? No db needed and much faster

    • @Adowrath
      @Adowrath Před 7 měsíci +2

      ​@@stevemartin2981How would a Factory help with validation that depends on context stored in the database?

  • @AJMansfield1
    @AJMansfield1 Před 10 měsíci +55

    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 Před 4 měsíci +1

      I know you said dynamic languages, but this all seems like non-problems that the compiler should enforce

  • @noherczeg
    @noherczeg Před 10 měsíci +17

    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 Před 10 měsíci +4

      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.)

  • @PhillipDressen
    @PhillipDressen Před 10 měsíci +38

    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 Před 7 měsíci +1

      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 Před 10 měsíci +83

    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 Před 10 měsíci +2

      Thank you!

    • @VideoWow7184
      @VideoWow7184 Před 9 měsíci

      Yep, read that one, it's really good.

    • @darkdreamflyer2317
      @darkdreamflyer2317 Před 8 měsíci +4

      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)

  • @kaanatakan
    @kaanatakan Před 10 měsíci +66

    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 Před 10 měsíci +20

      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 Před 10 měsíci +2

      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 Před 10 měsíci +8

      @@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 Před 9 měsíci +5

      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 Před 4 měsíci +3

      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.

  • @shanebenning
    @shanebenning Před 10 měsíci +58

    “… fixed TypeScript’s biggest problem” is the summoning ritual for Matt

    • @tech3425
      @tech3425 Před 10 měsíci +3

      Exactly what i thought 😂 If you say you've fixed a language's biggest problem...then you're Matt Pocock

    • @DrPizza92
      @DrPizza92 Před 10 měsíci +5

      What’s up wizards?

  • @user-yn8gk5gx5w
    @user-yn8gk5gx5w Před 10 měsíci +57

    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 Před 10 měsíci +2

      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 Před 9 měsíci +1

      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 Před 9 měsíci +3

      @@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 Před 9 měsíci +4

      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 Před 5 měsíci +3

      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.

  • @moraigna66
    @moraigna66 Před 10 měsíci +29

    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 Před 10 měsíci +7

      Yep - Fine with mocks - particularly on complex systems - yes they can get complex.

    • @Qrzychu92
      @Qrzychu92 Před 10 měsíci +6

      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 Před 10 měsíci +6

      @@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 Před 10 měsíci

      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 Před 9 měsíci +2

      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.

  • @drknoba
    @drknoba Před 10 měsíci +19

    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 Před 5 měsíci +8

      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

  • @fennecbesixdouze1794
    @fennecbesixdouze1794 Před 10 měsíci +14

    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 Před 10 měsíci

      so which is more idiomatic go? is it both?

    • @HonsHon
      @HonsHon Před 20 dny

      I do use them while being naked tbh. In fact, most languages in general I program while naked

  • @remrevo3944
    @remrevo3944 Před 9 měsíci

    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.

  • @alexaneals8194
    @alexaneals8194 Před 7 měsíci +2

    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.

  • @asdfasdf9477
    @asdfasdf9477 Před 10 měsíci +6

    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.

  • @EbonySeraphim
    @EbonySeraphim Před 9 měsíci +1

    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.

  • @bootdotdev
    @bootdotdev Před 10 měsíci +12

    LOVE TO SEE IT. Thanks for the read Prime

  • @theherk
    @theherk Před 10 měsíci +6

    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.

  • @TeaBroski
    @TeaBroski Před 5 měsíci +5

    you gotta appreciate the Ryan George "super easy, barely an inconvenient" quote

  • @pycz
    @pycz Před 10 měsíci +47

    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 Před 10 měsíci +10

      @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 Před 10 měsíci +3

      @@jarosawsmiejczak1138 Rails takes a similar approach iirc

    • @smallfox8623
      @smallfox8623 Před 10 měsíci +6

      testcontainers is great for this case

    • @QckSGaming
      @QckSGaming Před 10 měsíci +11

      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 Před 10 měsíci +6

      ⁠@@QckSGamingI realize in recent years that most people in this industry don't even understand the basic difference between unit test and integration test.

  • @krccmsitp2884
    @krccmsitp2884 Před 7 měsíci

    I love all of it, from the article and your reaction. 🙂

  • @misskalkuliert3976
    @misskalkuliert3976 Před 6 měsíci +7

    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 Před 4 měsíci

      Kinda same here. Did you find something?

    • @MrDasfried
      @MrDasfried Před 21 dnem

      Start writing small apllications for yourself/to learn/get projects done, would be my idea...

  • @anonimowelwiatko4455
    @anonimowelwiatko4455 Před 7 měsíci

    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.

  • @se4geniuses
    @se4geniuses Před 10 měsíci +12

    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.

  • @ripple123
    @ripple123 Před 10 měsíci +7

    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 Před 10 měsíci +1

      till you have one or two errors. When you have to handle 5+ probable errors your code becomes ugly.

    • @AJ213Probably
      @AJ213Probably Před 10 měsíci +2

      @@banatibor83 but is it better trying to handle 5+ probable errors that you don't know?

  • @axelfoley133
    @axelfoley133 Před 10 měsíci +20

    4:05 One doesn't simply insert Screen Rant memes into dev content.
    Bootdev: Actually it's super easy. Barely an inconvenience.

    • @sutirk
      @sutirk Před 10 měsíci +4

      Im gonna need you to get alll the way off his back

    • @bootdotdev
      @bootdotdev Před 10 měsíci +3

      OH REALLY

    • @Evan-dh5oq
      @Evan-dh5oq Před 10 měsíci +3

      It's definitely tight

    • @axelfoley133
      @axelfoley133 Před 10 měsíci +2

      @@sutirk ok well let me climb off that thing

    • @Patrick_Bard
      @Patrick_Bard Před 10 měsíci

      yeah yeah yeah

  • @jf3518
    @jf3518 Před 8 měsíci +1

    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

  • @user-dq7vo6dy7g
    @user-dq7vo6dy7g Před 8 měsíci

    How do I test the unit that calls saveUserInDB if validateUser was successful? At some point i need to moq those external resources.

  • @rosuewalford7767
    @rosuewalford7767 Před 7 měsíci +1

    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?

  • @TheJobCompany
    @TheJobCompany Před 10 měsíci

    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.

  • @kezzu5849
    @kezzu5849 Před 10 měsíci +6

    Shout out to the author for using "Super easy, barely an inconvenience" 😂 Pitch Meeting has reached the far reaches of the internet 🙏🏿

  • @bscharbau
    @bscharbau Před 10 měsíci +5

    How do you now test that the validation is actually performed before saving anything to the database without using a real database or mocks?

  • @KlemensSoftware
    @KlemensSoftware Před 6 měsíci +2

    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 Před 2 měsíci

      Docker solves this. Most languages have some integration with test containers, if not, it’s straightforward to roll your own.

  • @ScottLovenberg
    @ScottLovenberg Před 10 měsíci +54

    Yo dawg, we heard you like mocks....

    • @Thomas_Lo
      @Thomas_Lo Před 10 měsíci +2

      ...so we mocked your mocks.

    • @spl420
      @spl420 Před 10 měsíci +2

      ​@@Thomas_Loso you can mock your mocks while you are mocking your mocks.

  • @michaelharrington6698
    @michaelharrington6698 Před 9 měsíci +1

    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.

  • @spicynoodle7419
    @spicynoodle7419 Před 10 měsíci +15

    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 Před 10 měsíci +3

      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 Před 10 měsíci

      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 Před 10 měsíci +2

      @@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 Před 10 měsíci

      @@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 Před 10 měsíci

      @@alanonym8972 you should use something like Sentry to report exceptions, no need to rely on users.

  • @vytah
    @vytah Před 10 měsíci +1

    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.

  • @BorisTheDev
    @BorisTheDev Před 10 měsíci +7

    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.

  • @LEGnewTube
    @LEGnewTube Před 10 měsíci +7

    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 Před 10 měsíci +2

      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 Před 10 měsíci +7

      @@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 Před 10 měsíci +3

      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 Před 10 měsíci +2

      A more accurate statement would be you shouldn’t mock in unit tests

    • @LEGnewTube
      @LEGnewTube Před 10 měsíci +3

      @@ashvinnihalani8821 Sure, but if you need to test the whole flow of the main function than you would need to use a mock.

  • @Milotiiic
    @Milotiiic Před 5 měsíci +1

    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

  • @marcgentner1322
    @marcgentner1322 Před 10 měsíci +1

    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?

  • @pranavrajveer3767
    @pranavrajveer3767 Před 7 měsíci

    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

  • @StevenHunt1
    @StevenHunt1 Před 3 měsíci

    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.

  • @ClaytonHarbich
    @ClaytonHarbich Před 5 měsíci +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?

  • @comodsuda
    @comodsuda Před 5 měsíci +1

    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.

  • @khatdubell
    @khatdubell Před 10 měsíci

    Depends on what you're mocking, and how.
    I frequently mock network components

  • @morgengabe1
    @morgengabe1 Před 10 měsíci +1

    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.

  • @briankarcher8338
    @briankarcher8338 Před 5 měsíci

    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?

  • @AScribblingTurtle
    @AScribblingTurtle Před 10 měsíci +3

    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  Před 10 měsíci +1

      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 :)

  • @NilMNV
    @NilMNV Před 10 měsíci +2

    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.

  • @ivanovichru510
    @ivanovichru510 Před 10 měsíci

    Love the Ryan George "Super easy, barely an inconvenience".

  • @autohmae
    @autohmae Před 5 měsíci

    8:44 don't specifically need ORM, just an encapsulation function to not do it raw. A function which generates the SQL.

  • @LordOfElm
    @LordOfElm Před 10 měsíci +8

    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  Před 10 měsíci +4

      this second idea is really good idea

    • @gentooman
      @gentooman Před 10 měsíci +2

      >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 Před 10 měsíci +1

      @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 Před 10 měsíci

      ​@@LordOfElm You sound just like every other junior developer who hates writing tests.

    • @NathanHedglin
      @NathanHedglin Před 10 měsíci

      ​@@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? 😂

  • @marcbotnope1728
    @marcbotnope1728 Před 10 měsíci +4

    Check your unit tests privilege! Some of us are happy if there are any automated testst at all.

  • @im-luke
    @im-luke Před 5 měsíci +1

    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.

  • @valcron-1000
    @valcron-1000 Před 10 měsíci +2

    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 Před 10 měsíci +1

      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 Před 10 měsíci

      @@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.

  • @irreadings
    @irreadings Před 9 měsíci

    Oh man I laughed out loud at that hand on face joke. This doesn't happen where I live

  • @teaman7v
    @teaman7v Před 10 měsíci

    Great article

  • @allalphazerobeta8643
    @allalphazerobeta8643 Před 10 měsíci +4

    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
    }

  • @zevo92
    @zevo92 Před 10 měsíci +2

    1:36 minutes into the video, am already very much entertained. I love this man :X (Disclaimer: In a very platonic way)

  • @Optable
    @Optable Před 6 měsíci +1

    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

  • @wbtittle
    @wbtittle Před 7 měsíci

    God Bless You.

  • @chiefxtrc
    @chiefxtrc Před 10 měsíci +3

    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 Před 10 měsíci +1

      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 Před 10 měsíci +1

      @@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.

  • @cubbucca
    @cubbucca Před 10 měsíci

    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.

  • @albucc
    @albucc Před 10 měsíci +5

    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 Před 10 měsíci

      @@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 Před 10 měsíci +2

      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 Před 9 dny

      @@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.

  • @adamstrejcovsky8257
    @adamstrejcovsky8257 Před 8 měsíci +1

    The thing about mocks and unit tests, they look useless until you run them😂then you are happy you have wrote them

  • @petedisalvo
    @petedisalvo Před 4 měsíci +1

    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.

  • @vincenthamel3420
    @vincenthamel3420 Před 3 měsíci

    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.

  • @valkhorn
    @valkhorn Před 10 měsíci +1

    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?

  • @stevemartin2981
    @stevemartin2981 Před 7 měsíci

    I ❤❤ mocks personally. I am a mockist through and through. Factories make it so effective

  • @SemiMono
    @SemiMono Před 10 měsíci +1

    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.

  • @scottwalker4619
    @scottwalker4619 Před 2 měsíci

    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.

  • @Aralmo640
    @Aralmo640 Před 7 měsíci +1

    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.

  • @atiagosoares
    @atiagosoares Před 9 měsíci

    This video cured me of my dependency injection

  • @tdiblik
    @tdiblik Před 10 měsíci +1

    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 Před 7 měsíci

      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.

  • @johngagon
    @johngagon Před 9 měsíci

    the funkiest diddling I've heard in a long time.

  • @klamberext
    @klamberext Před 3 měsíci

    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.

  • @r2-p2
    @r2-p2 Před 6 měsíci

    How do you test a class (having internal state) with dependencies without mocking the dependencies?

  • @ybcoding5153
    @ybcoding5153 Před 4 měsíci

    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.

  • @bobross6228
    @bobross6228 Před 9 měsíci

    Scariest thing here was the naked squeal

  • @user-oy3ok1qd2y
    @user-oy3ok1qd2y Před 7 měsíci

    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🧐

  • @DNHRobot
    @DNHRobot Před měsícem

    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

  • @terjemahanminda-ahmadfahmi6343

    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?

  • @peachezprogramming
    @peachezprogramming Před 6 měsíci

    as an aspiring backend dev, I am so happy i understand this

  • @hellowill
    @hellowill Před 7 měsíci

    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.

  • @NyaowYeon
    @NyaowYeon Před 10 měsíci

    Thanks

  • @ClintonChelak
    @ClintonChelak Před 9 měsíci

    8:00 The sound of silence can be pretty intense, though notably he changed to more silence.

  • @SurfsUpSeth
    @SurfsUpSeth Před 9 měsíci

    This guy could be a voice actor for English dubbed anime’s

  • @bennguyen1313
    @bennguyen1313 Před 2 měsíci

    Any idea how Comma AI does its (regression) testing? I assume they use an open-source tool (CppUTest, google test , catch2, doctest) but what?

  • @JefersonEuclides
    @JefersonEuclides Před 9 měsíci

    As a NodeJS developer, I'll say this: I laughed, a lot.
    Then cried, just a bit.

  • @venir_dev
    @venir_dev Před 9 měsíci +1

    So, in a nutshell: write stubs, not mocks..?

  • @emjizone
    @emjizone Před 9 měsíci +1

    Are mocks a way for devs to make things fail in spite they failed to introduce bugs in the test functions ?

    • @alienrenders
      @alienrenders Před 3 měsíci

      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.

  • @skudge
    @skudge Před 8 měsíci

    last company i worked for refused to let use use an orm and we had to raw-dog sql everywhere

  • @GnomeEU
    @GnomeEU Před 9 měsíci

    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.

  • @antdok9573
    @antdok9573 Před 9 měsíci

    I'm in a huge agreement with being against mocking for many scenarios.
    However, 5:16, this is not a very good testing strategy... You should know what your expected value is when you're unit-testing, through-and-through and this isn't an enough of actual usage of code as far as the behavior you get when invoking functions for it to be an acceptance/integration test. You do not want to use actual output as expected test data, let alone this is not even possible for sensitive information that is protected for privacy sake. You really only want to do snapshot/approval style tests when you're refactoring legacy code, and not necessarily adding/removing features.
    The downside of using your production data in test is that you're nailing down the existing state of your data rather than creating a new feature. It can lead to fragile tests. A database most of all would be one thing I would expect to frequently change. A unit test in this style for a small behavior would be much less fragile.

  • @retagainez
    @retagainez Před 9 dny

    You don't need a mock object, but you easily could've written a Fake implementation of a database, like an in-memory database class, to accomplish this. That way, you can test the implementation of user validation and database operation without changing production code and then start writing new unit tests for new functionality.
    A mock would be overkill.

  • @nryle
    @nryle Před 4 měsíci +1

    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.

  • @elementotriplo4966
    @elementotriplo4966 Před 10 měsíci +1

    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 Před 10 měsíci +3

      No, you should not. Your tests are fine.