How To Write Unit Tests (The Right Way)

  Рет қаралды 38,090

Cody Engel

Cody Engel

Күн бұрын

In this video I will teach you how to write better unit tests in under 15 minutes. Throughout my career I've had the opportunity to teach other software engineers about effective unit testing. Honestly, these skills are not too difficult to master once you understand what they are. In this video we will discuss what unit tests are, why you should only test your code's behavior, how to simplify your unit test setup, why one assertion per test is enough, and why it's important to keep your unit tests isolated from one another. Wow, what a run-on sentence that was. While we won't go over how to do test driven development in this video, this is a really good prerequisite for that.
🚶‍♂️ FOLLOW ME 🚶‍♂️
Discord - / discord
Twitter - / codyengeltweets
Medium - / codyengel
⏰ TIMESTAMPS ⏰
0:00 - Intro
1:24 - What Are Unit Tests
2:02 - Test The Code's Behavior
3:30 - Simplify Unit Test Setup Process
7:36 - One Assertion Per Unit Test
10:00 - Keep Unit Tests Isolated
🎥 CAMERA GEAR 🎥
Camera - amzn.to/2LM9Zt3
Microphone - amzn.to/37AAj2G
Lens - amzn.to/317tGPT
Main Lights - amzn.to/2K2yHDH
External Monitor - amzn.to/2YoM2Kl
* Note: the above links are affiliate links.
🖥 DESK GEAR 🖥
Monitor - amzn.to/2yjZPqR
Headphones - amzn.to/2YBuo68
MacBook Pro 2019 - amzn.to/30YyuXy
* Note: the above links are affiliate links.
Try Epidemic Sound: www.epidemicsound.com/referra...
#unittesting #softwareengineer #softwaredeveloper

Пікірлер: 75
@CodyEngelCodes
@CodyEngelCodes 3 жыл бұрын
What are your favorite tips for writing good unit tests?
@anthonylosego
@anthonylosego 2 жыл бұрын
My like button turns white in dark mode, not blue.... unit test giving false negative = fail. lol This is how a staff software engineer writes good unit tests? sigh... (Yanking your chain btw... kinda...)
@segevmalool9072
@segevmalool9072 2 жыл бұрын
Only mock operational dependencies (not code dependencies) and use a property-based testing lib!
@armanmasangkay6513
@armanmasangkay6513 Жыл бұрын
Don't mock code you don't own.
@erastvandoren
@erastvandoren Жыл бұрын
Don't write them.
@erastvandoren
@erastvandoren Жыл бұрын
@@anthonylosego My like button turns black 😆
@DedicatedManagers
@DedicatedManagers 3 жыл бұрын
Would love to see you teach a beginner tutorial on unit testing. It would be really awesome to learn unit testing from someone with such vast industry experience.
@CodyEngelCodes
@CodyEngelCodes 3 жыл бұрын
Thanks, with the TDD video I’ll try to include more specific examples. I’m trying to shy away from uploading full blown coding tutorials on KZbin, but I think I can do more to give better examples in these videos.
@DedicatedManagers
@DedicatedManagers 3 жыл бұрын
Why are you shying away from full tutorials?
@CodyEngelCodes
@CodyEngelCodes 3 жыл бұрын
The last one I did (Kotlin Collections) took me 2 months to find the will to edit the videos. I also don’t think I’m able to support the comments on those videos as well as I’d like to. I definitely want to make these videos again in the future but they would probably be on Udacity or some other platform (I’d like to keep the courses affordable so between $9.99 and $19.99, or “free” if it was on Skillshare). I do think I can mix in code samples in these videos better going forward though.
@LyricWulf
@LyricWulf 3 жыл бұрын
test_like_button ✅ *[PASSED]* (1m21.69s)
@levon9
@levon9 5 ай бұрын
Wow ... really useful, thank you so much for sharing. Also, subscribed :)
@CodyEngelCodes
@CodyEngelCodes 5 ай бұрын
Really happy this was helpful!
@fluffyfetlocks
@fluffyfetlocks Жыл бұрын
I’ve had that same experience of having limited understanding meaning that there’s a communication issue
@nalinitippa5942
@nalinitippa5942 2 жыл бұрын
Great content . Thanks a ton and much respect for your efforts here. Could you please share how you evaluate new software libraries? how to evaluate Android libraries to see how they fit the needs of an Android application. What kind of metrics do you generate and how ? If you could walk through with an example( like evaluating Room library or Hilt ).Specifically, How do you evaluate a software library for scalability. What tools or tests help? Thanks again.
@CodyEngelCodes
@CodyEngelCodes 2 жыл бұрын
Hey I'm not sure if I could do an entire dedicated video on that. I mostly look for community sentiment, support from the maintainers of the library, as well as if the license is compatible with my project. Hope this helps, I'll think about how I could make this into a video in the future.
@nalinitippa5942
@nalinitippa5942 2 жыл бұрын
@@CodyEngelCodes Got it, Sure. Thankyou.
@PatrickSteil
@PatrickSteil Жыл бұрын
How about for a string parameter testing blank, a normal size string and a string that is too long. I assume these would be 3 different unit tests, correct?
@CodyEngelCodes
@CodyEngelCodes Жыл бұрын
If those are important behaviors to your application then yes they would be 3 different tests! Although it all depends on which behaviors are important to capture and test around.
@christopherwilson8700
@christopherwilson8700 Жыл бұрын
I am a teacher and I've been trying to write tests for my students. However, there are not any good tutorials for testing the main method of a class. When I am teaching constants, I want to test that they are setting specific variable to a constant, and using the convention of capitalizing a constant variable. Would you be able to help with this?
@CodyEngelCodes
@CodyEngelCodes Жыл бұрын
I wouldn't unit test that and instead rely on a linter to make sure the constant variable is always capitalized. I wouldn't write a test to validate that a constant was set to the correct value (just not a terribly useful test). If it's necessary though, you could always write a test that validates the constant is the correct value, shouldn't need to test around the main method for that, just spin up a test function and assert the value of the constant.
@CallousCoder
@CallousCoder Жыл бұрын
That’s not unit testing, that’s automated code review. You would need to do this in a linter or a code quality tool like sonarqube where you can even specify these. But who cares if it’s a capital or not? To me that’s triviality. I like consts to be capitalized but it not then fine. But Rust or example doesn’t even allow you to compile. And you can set this up for C++ too.
@wjrasmussen666
@wjrasmussen666 Жыл бұрын
wish you had code examples for everything you pointed out, like the factories.
@CodyEngelCodes
@CodyEngelCodes Жыл бұрын
That'd turn this into a really long video lol. I would like to create something more robust in the future, although that'd likely be a course because it would flop on KZbin.
@preneshreeperumal7379
@preneshreeperumal7379 Жыл бұрын
Hi Cody can you recommend C# unit tests 'how to'?
@CodyEngelCodes
@CodyEngelCodes Жыл бұрын
Unfortunately I cannot 😭 hopefully there are some channels out there that are covering this, but if not maybe it's something I can work on in the future.
@segevmalool9072
@segevmalool9072 2 жыл бұрын
Check out jquick (java), fast-check (js), hypothesis (python)... best property-based testing libs with support for arbitraries (which were called "factories" in the video)
@CodyEngelCodes
@CodyEngelCodes 2 жыл бұрын
Thanks for the recommendation!
@fredlyw1990
@fredlyw1990 Жыл бұрын
How do you write unit tests for a long class method having 1500+ lines of code? Also it has lots of global dependencies (in a form of class static methods). The test case I set up has 100+ lines just for mocking so as to get to the line of code I am asserting. OMG
@HoD999x
@HoD999x Жыл бұрын
don't try. rewrite that thing.
@CodyEngelCodes
@CodyEngelCodes Жыл бұрын
You don't. You leave that dumpster alone so it can burn while you work on replacing it with code that is maintainable and testable.
@brandonw.2066
@brandonw.2066 3 жыл бұрын
package smash.that.like.button had me dying laughing.
@CodyEngelCodes
@CodyEngelCodes 3 жыл бұрын
😂 really stoked that you caught that.
@dansteryoo
@dansteryoo 3 жыл бұрын
Can you give actual examples with code next time? This was great! Thanks!!!
@dansteryoo
@dansteryoo 3 жыл бұрын
I meant more like a walk-through tutorial.. haha.
@CodyEngelCodes
@CodyEngelCodes 3 жыл бұрын
Gotcha thanks for clarifying 😅 I tried to include some smaller samples with b roll, but to your point, it wasn’t super in-depth. I can go more in-depth with my test driven development video.
@dansteryoo
@dansteryoo 3 жыл бұрын
@@CodyEngelCodes Yeah, when I first found your channel a year back.. I thought you gave the most insight that was more in-depth (with specifics) than what I saw in other channels (which was flashy but vague). Like a yt-mentor for younger coders haha. Keep it up!
@CodyEngelCodes
@CodyEngelCodes 3 жыл бұрын
Thank you, that means a lot 🥲
@SaintSaint
@SaintSaint Жыл бұрын
If you used his idea of random number/string generators, make absolute certain to include the generated string in your messaging. Otherwise, tests will sporadically fail and you will have to suss out the input that made them fail.
@SaintSaint
@SaintSaint Жыл бұрын
Also, a good generator/list to have is a minMaxZeroOneNegOne.
@SaintSaint
@SaintSaint Жыл бұрын
I've never had much luck with auto-generated unit tests.
@CodyEngelCodes
@CodyEngelCodes Жыл бұрын
The failures should show up in the failure message "expected: blah, but was blahh" as an example. Also make certain the values do not actually matter, randomly generated values are only useful when the test can be written in such a way that the exact value is not important.
@danielwilkowski5899
@danielwilkowski5899 Жыл бұрын
I don't think using "random" is the best idea. Perhaps writing "fake" string, but one that doesn't change from run to run would be better.
@CodyEngelCodes
@CodyEngelCodes Жыл бұрын
It depends, in situations where the value itself doesn't matter then using random can help to illustrate that. With that said, using hardcoded values for testing is probably the way to go, especially when coupled with parameterized tests.
@danielwilkowski5899
@danielwilkowski5899 Жыл бұрын
@@CodyEngelCodes i see your Point - show to the Reader that the exact value doesnt matter. Thats a valid Point, but I have found a better way to do it. Pick a Word project-wise, any Word. I pick Word "dummy", "foo" or "bumbum" and I put that Word wherever the exact value doesnt matter. I prefer it, because i hate when test fail randonly, like run it 100 times and 99 times it passed and 1 time it fails. Random with a seed value which always generates the same valuss is Also acceptable, but test that actually puts different values into the test is a horrible mistake IMO.
@davyncox5005
@davyncox5005 Жыл бұрын
Like button test needs to be updated
@CodyEngelCodes
@CodyEngelCodes Жыл бұрын
I keep asking KZbin to fix it but alas my cries for help have gone unheard.
@linkinparkonstage
@linkinparkonstage 2 жыл бұрын
Tests with random data generation are not reproducible. Not a very Staff thing to do.
@CodyEngelCodes
@CodyEngelCodes 2 жыл бұрын
If the underlying data doesn't matter, then using random data is a good route to take. If you need to validate that emails ending in @gmail.com are handled differently, then yeah, you probably don't want to use random data for those tests.
@zyph.
@zyph. 2 жыл бұрын
I have to agree here. If there’s no need for the data to be random, just use a static string or number. The unit test should have predictable input and output, and be fully reproducible. As you mention in the video, it should be isolated and pass every single time. And random generators are even platform specific.
@travisx4919
@travisx4919 2 жыл бұрын
yeah, with random data no matter how much you are confident it won't happen, there's always a chance for the test to fail on one run but pass on the other, which is super hard to debug.
@BuffNerdInCa
@BuffNerdInCa 2 жыл бұрын
They are reproducible due to standard computer pseudo random number generators. Use same seed. This is the bases behind recorded game play, for example, in video games.
@mystartupjourney5283
@mystartupjourney5283 2 жыл бұрын
test_like_button ❌ *[Failed]* --> it turned black :D
@CodyEngelCodes
@CodyEngelCodes 2 жыл бұрын
Oh no!!!
@khatdubell
@khatdubell Жыл бұрын
You need to expand your definition of unit test, imo. A unit test needs to be standalone runnable from the command line. A unit test needs to be executed as part of your build pipeline. If those two things aren't true, you aren't really unit testing, you're just testing imo. Those two things impose a third restriction on unit tests. They need to be fast.
@CodyEngelCodes
@CodyEngelCodes Жыл бұрын
I think the first part makes sense. I don't think they need to be executed as part of a build pipeline, once they are, they move from being unit tests to being automated unit tests. Which for the record I do think it's a waste of time to write regular unit tests, you should only write automated unit tests. ...So probably on the same page but maybe some different semantics?
@CallousCoder
@CallousCoder Жыл бұрын
@@CodyEngelCodes unit tests that run from the cli also run form a build pipeline. This is the way to go. Because then you rubbing them before checking in your code to the remote branch. This helps also with reverts because you know what is in the branch at least last your unit tests. And of course you want the tests to be run as well as part of your commit. So that when you do a PR the team lead knows that the tests ran fine because otherwise you shouldn’t be able to do a PR.
@wjrasmussen666
@wjrasmussen666 Жыл бұрын
The down didn't turn blue.
@CodyEngelCodes
@CodyEngelCodes Жыл бұрын
I keep telling KZbin to fix it and they keep ignoring me.
@MrAlex9939
@MrAlex9939 2 жыл бұрын
My like button turned white, test failed
@CodyEngelCodes
@CodyEngelCodes 2 жыл бұрын
Dang it!
@roylopezaraiza3903
@roylopezaraiza3903 Жыл бұрын
The like button turned black for me :c
@CodyEngelCodes
@CodyEngelCodes Жыл бұрын
Oh no!
@riancox
@riancox Жыл бұрын
My "Like" button failed the unit test. Exploded with color and went white. Please review your code.
@CodyEngelCodes
@CodyEngelCodes Жыл бұрын
I keep asking KZbin to fix the like button but my cries for help have been ignored.
@KeithBarrowsToday
@KeithBarrowsToday 8 ай бұрын
Like button: Fail. Original state = white outline, black fill. OnClick = Flashed red then turned white and solid.
@bantoniow
@bantoniow Жыл бұрын
IT'S BLACK We need to rewrite tests for like button!
@fennecbesixdouze1794
@fennecbesixdouze1794 10 ай бұрын
Wow this advice is unbelievably terrible. For the love of god DO NOT generate random inputs for tests.
@CodyEngelCodes
@CodyEngelCodes 10 ай бұрын
Why not? If the specific values are not necessary for the test then why waste the energy typing in random values as opposed to using something that will just generate a random value. Yes, if the value is indeed necessary for the test, then do not use a random value.
@vishwasrv
@vishwasrv 9 ай бұрын
Just dont write tests , its useless to unit test , a big waste of time
@vyli1
@vyli1 5 ай бұрын
so how do you make sure your refactoring didn't break anything? Do you manually test the whole application? That becomes infeasible at a certain scale.
@vishwasrv
@vishwasrv 5 ай бұрын
@@vyli1 there are automation tests that can check that during CI
@vyli1
@vyli1 5 ай бұрын
@@vishwasrv Unit tests are automated tests that are usually run on CI pipeline. So unit tests do fall into this category, which makes me think you're talking about something else. It's fine as long as those tests are very fast, test all the possible scenarios, are easy to maintain and are run before code is merged to the main branch. If none of the above is true, you need unit tests.
Effective Unit Testing by Eliotte Rusty Harold
48:10
Devoxx
Рет қаралды 102 М.
Theo Doesn't Write Unit Tests (This Is Why You Should)
13:01
Cody Engel
Рет қаралды 8 М.
How Many Balloons Does It Take To Fly?
00:18
MrBeast
Рет қаралды 156 МЛН
That's how money comes into our family
00:14
Mamasoboliha
Рет қаралды 12 МЛН
Best father #shorts by Secret Vlog
00:18
Secret Vlog
Рет қаралды 22 МЛН
The 3 Types of Unit Test in TDD
17:19
Continuous Delivery
Рет қаралды 100 М.
When To Unit, E2E, And Integration Test
14:58
ThePrimeTime
Рет қаралды 91 М.
When You Ask the Intern to Review Your Code
4:01
Nicholas T.
Рет қаралды 565 М.
How To Write Unit Tests For Existing Python Code // Part 1 of 2
25:07
Clean Code Is Killing Your Projects
9:20
Web Dev Simplified
Рет қаралды 144 М.
How Senior Programmers ACTUALLY Write Code
13:37
Thriving Technologist
Рет қаралды 1,4 МЛН
Unit Testing Is The BARE MINIMUM
20:33
Continuous Delivery
Рет қаралды 31 М.
Agile Has Destroyed Programming - Here's How To Fix It
12:16
Cody Engel
Рет қаралды 44 М.
You Can't Unit Test C, Right?
23:09
LinuxConfAu 2018 - Sydney, Australia
Рет қаралды 51 М.
How Many Balloons Does It Take To Fly?
00:18
MrBeast
Рет қаралды 156 МЛН