Excellent. Part of it is just wanting everyone to relax and not think you have to be perfect (I'm sure not). Part of it is that I do think it shows a realistic view on what I do as a developer. I am glad it is helpful to you.
0:00 - Intro 1:37 - Working environment 3:35 - Demo application walk-through 7:14 - Unit Testing explained 9:45 - Creating a Unit Test project 13:22 - Setting up a test 22:37 - A bad Unit Test and Test Driven Development 25:48 - Opinion on Unit Testing 28:40 - Shortening Test name 31:08 - "Theory": Test method parameters and arguments 36:09 - Testing edge cases 38:43 - Testing number division 43:13 - Dividing by zero 48:55 - Testing methods that can throw exceptions: method returns output 54:14 - Debugging the Unit Test 55:19 - Testing the exceptions: method throws exception 59:22 - Testing the exceptions: method argument throws exception 1:05:07 - Testing methods that do more than one thing: what is a Unit of work? 1:10:56 - Breaking method in to individual methods, what to test and what not to test 1:18:50 - "Add to List" Tests: working test 1:26:50 - "Add to List" Tests: failing test 1:35:37 - Homework 1:40:05 - Concluding remarks
This was a truly great video. Not only was the educational content about the specific subject matter of unit testing fantastic, but also, just taking the time to carefully convey the fundamentals serves to remind us all that development and engineering is not about just quickly getting through things, but that it is about long term excellence and profound understanding.
Thank you for this one, as well! One note, being 5 years later, adding the project as xUnit Test Project, allows for selection of newer .NET versions. Using the Class Library (.NET Framework), doesn't allow going beyond .NET v4.x. Which slightly changes how to add the project references from Dependencies>right click>Add Project Reference.
This is how you make a tutorial! All of them all greate. I was like test code cost me more time but now I see the benefits and expecialy how you show it in this tutorial
This one is like attending a psychologist, thank you so much, I've been programming more than 10 years but learned about testing only recently, same with design patterns, all because I usually programmed alone and never cared about what others are doing, but now I feel like incompetent which hinders me even at employment, though I decided to go through all your learning path videos and fix this )) Thank you!
I might have to subscribe to Tim Corey... (jk - I already did). This course is, what, 4 years old and yet, it's still applicable today. Easily, one of the best intros to unit testing I've ever seen. Thanks for posting this!
Hi Tim. Thanks for the great tutorial (and the follow up Moq video). I've always grumbled about testing, but this has opened my eyes to see that it can really be super satisfying and fun. I've had lots of fun today extending your sample project with tests for the CSV serialize/deserialize and theories around handling bad input etc. All round top notch stuff, thanks mate!
@@IAmTimCorey Also, I agree 100% w/ your philosophy on the testing fanatics. They have definitely deterred me from getting into Unit Testing in the past. Thanks for the help.
Tim, your words about TDD fanatics is really important. I (and I guess lot of us) feel I'm not good enough because I haven't written lot of tests in my career. That's brings some guilt for me. You say 10 is better than 0, 11 is better than 10. That sentence give me a hope and ability to stay calmly focus and slowly building my skills in tests area. Thanks you Tim!
wow. recently started a new job and was a bit overwhelmed with the unit testing and mocks but found this video extremely helpful. I feel a little more confident about them now. Thank you so much! subscribed :)
This video not just covers unit testing but also the way we extract and extract and extract following Single Responsibility Principle and Clean Code. Thank tou Tim Corey
Thanks for the detailed walkthrough! A question, what if I just want to check whether an exception is thrown, and don't care about the exception type? Asset.Throws seems to work with the specific type only.
Back in '93 when I started my programming career, we built our requirements using Test Cases. Then we built the code using the Test Cases. Later, when Test script tools came along, Test Data was stored separately and 'pulled' into the test script. It allowed for a much easier and larger test bed. It's true as you said, you can go overboard with your testing. I basically test upper and lower bounds, test data types, test Nulls, and finally test real--life scenarios (using recorded scripts).
Hi Tim, I would like to thank you, Your Videos was very useful for me, I mean not only this tutorial but also almost every videos i watched until now. Thanks again🙏
I recectly was put to work in doing some small projects and testing them in my company where I work as a student worker. They used XUnit, Moq, and Autofixture, and this video is definetly a good start to build upon. Once done, I need to watch something in Moq and Autofixture, but this really makes things easier :)
Actually I stayed up late. My window to record (when the house is quiet since I don't have a dedicated soundproof studio) is between 10pm and whenever I'm done. Usually that means midnight or 1am but sometimes it goes longer.
Great video, as always. I've worked with xUnit before but now I've learned a lot of xUnit, unit tests and best practices. Thank you for sharing your knowledge. I'm definitively going to practice it right away. =)
Great advice on testing! I agree, that it doesn't have to be all or nothing, even some tests can help you out a lot. I have a few tests for my ahk project, for stuff that I wanted to test while developing. It's like 2% code coverage, but those tests definitely help to make absolute sure *that* part of code works. If I didn't have them, it'd be 0% and that's obviously worse. Better to do a bit than no bit!
Hi Tim, great video as always! :d I have seen multiple videos where you hard coded the name of a property, so i think you missed a cool feature of c#, since c# 6, you can use the "nameof()" keyword to get the name of a type or member as string at compile time (ie. namof(Person.FirstName)) so the code will not break if you rename FirstName to something else. There is a similar keyword called "typeof()", which you can use to get a compile time Type variable, and you can even use it on T types.
I believe this video (and I know quite a few others were as well) was done before C# 6 came out (or at least I wasn't using it yet). I did miss it on a few videos after it came out but I do use it now and love it! Thanks for bringing it up.
Great video Tim, first time I get into unit testing and I really like your slow / calmed pace of teaching, the pauses you make are key to be able to graps the concepts of what you're explaining. I will be doing the homework on this project now :)
Great lesson. My only feedback is that it would be great if the provided source code was from the state of the VS Solution from the start rather than after you made the changes so we can learn by actually making those changes ourselves.
It would be great to have a tutorial on the subject of Unit tests VS Integration tests and how to use Dependency Injection to isolate units and convert Integration tests to Unit tests
Im currently studying to become a fullstack developer. Unfortunately, even though my teachers are very skilled and knowledgeable, they are somewhat lacking in the pedagogic. Your videos are amazing complimentary to understand the fundamentals of subjects that I sometimes find hard to grasp. Big thank you!
@@IAmTimCorey I have to keep rewatching until I get it. I tried testing some methods today and I couldn't figure out how to make the test pass. I am lost.
It might look frightening and over the top to do unit testing in the early stage of your coding. But this is actually a time where testing have helped me in C# a lot. Like Tim says it forces you to write sensible and well structured code from the start. And it will also make it clearer for you on "what do next". It basically solves a lot of the uncertainty you always have bet a bit extra as a beginner. And with the boosted confidence you will move forward faster. This is my belief.
Hi Tim. Great video but I do have a question in relation to Test Driven Design. If you write the "test" first, this would mean in your test you would be calling a method which doesn't exist yet. So your test wouldn't fail... it wouldn't compile and run at all. So just for clarification, is the idea that you write the test... but put in something "hard coded" to represent a failure scenario. This get's you the red light as you put it. Then write the method, and swap the hard coded value for the method call in order to get the green light?
Create the method stub and then write the test. That way, the test fails but everything compiles. Usually if a method has a return, I add a "throw new NotImplementedException();" so that it does compile. That way, when you write the "real" code, the test will go from red to green.
This was amazing and far clearer and easier to understand than other videos which basically just cover an add method. Would have like to see a fully fleshed out suite of tests for 1 method though. I'm curious if you would test things like if an argument was null etc even though it would normally be handled on the front end before it reaches the back end code for example.
I test the things that can happen. If there is no way for that to happen, I probably wouldn't test for it. Although, that's probably a rare case. Usually, I plan for that eventuality in my code so then I test for it.
Test Driven Development people? Hmm :-) You really highlight the issues, in a nice way, why people do not use TDD, and this video is a fine example on why it makes sense to use unit testing and why TDD is a strong tool in development
Can you create a video about how to do integration testing? Do you just create a separate test project and use real external sources? Obviously they wouldn't be production they would be test systems that are backups of production.
Great video - as always! You really help me learn to write much better code. Thank you so much! Will you show different forms of testing in upcoming videos (i.e. end to end testing or more advanced unit tests)? That would be really helpful!
Yes, I will be covering other testing types in future videos. First I want to cover more about unit testing though (mocking is the biggest area to cover yet).
The video was very helpful as usual, thank you!! I'm looking forward to learning about mocking and perhaps also how to test private methods with XUnit (as I'm unsure all my smaller "helper methods" should be public just to make them easily testable.. That would go against my attempts at encapsulation. But I do want to test them.). I'm also looking forward to an intro to integration and end to end testing sometime in the future but I know you get a LOT of video requests.
Hi IAMTimCorey, just wanted to ask you something about the part where you talk about not moking microsoft calls (File class in your example). So, In the case you have there where you add a person object to a list and then to file. If I understood correclty, you prefer to unit test the little bits not dependant of external things (like file system), and then test all the function (that contains the File call) in an integration test. Am I right? I like this idea because I also think that almost any method can be splitted and there would be parts really hard to unit test. Mainly external dependecies like DbContext or DBset, etc. The sensible thing to do here, is unit test what can be unit tested and then delegate the other stuff to an integration test. Do we agree?
Usually if you are following SRP and other good OOP principles, you can unit test just about everything. I don't go crazy with that theory but it does make you re-think how you write code when you are considering how to make it testable. Unit tests should test one unit (one specific thing). Then, you can test the interaction of things together in an integration test, so yes, I think we agree.
Hi Tim, been following you for a couple of weeks by now and I'd like to leave a couple of notes based on experience. Following a TDD approach I'd have written the test first for the DataAccess class instead of refactoring because (supposing it's a real life situation where your DataAccess is actually working) you wouldn't be sure if your class continued to work after the refactoring. The other thing is that your testing approach would only work with classes that are more structured-oriented or functional-oriented than object-oriented (for example, classes with lots of public methods that are either static or don't keep instance attributes). In real object-oriented unit testing the smallest unit of code to test is not a single method but the class as a whole calling the minimum amount of methods required for the class to work (for example in a BankAccount class the minimum unit testing could be create the account, deposit a small amount of money, request the balance, withdraw the money and close the account). This is a mistake done by many (if not most) programmers wanting to start unit testing and also TDD supporters. And no, I'm not one of those mad zealots :) but if you test only a method in a class that had 5 instance attributes you will virtually skip every state where the attribute work for your tested method but breaks every other method. Best regards
I tried not to go down the TDD road because if you are just learning unit testing, you probably have existing code that needs to be tested. As for the working with classes instead of methods, this sounds more like integration testing than unit testing. You can test the individual methods and just identify the various inputs and outputs where a changed value occurs and then test to those values.
Thanks for the video! I'm just starting to get my feet wet with unit testing after a couple years of programming. I've been running into situations where I've changed code and things break. My applications are complex enough where it would be quite a pain to try and manually test for possible errors. It's also rather difficult to think of every possible thing that can go wrong when I make a change. It's nice to build tests that continue to run automatically as the application is built so that I don't have a growing list of things to check for before I deploy updates. One small thing I've noticed in your videos is that there is a slight delay between the video and the audio. I'll see the cursor (blinky text editing thing) move on your screen then about half a second later I'll hear a mouse click. It would nice if the audio was perfectly in sync with the video. It's slightly distracting, but not a huge deal. Great videos though. Probably the best on the internet for learning code as far as I'm concerned.
I've noticed that issue and corrected going forward (mostly). There is a bug in the software I use to record that sometimes allows it to get out of sync. I haven't tracked down why yet and it only happens occasionally now but I try to fix it when I catch it in time.
Question: At 45:45, where you get an error on your Divide_DivideByZero test, my test passes without error. I've searched, but can't find if this "divide by zero" error no longer applies in VS19? Does anyone know? I've triple checked and my code is the same as in the video. Cheers
I have a question regarding the breaking bigger method to bunch of separted methods (Around 1:10:00 ) . Doesn't it create dozens of public methods that make this class ridicolous in use (lots of methods to choose from when only part of the are really necessary) ?
Breaking a big method into smaller methods helps us accomplish SRP ( th-cam.com/video/5RwhyZnVRS8/w-d-xo.html ). It does mean we have more options to choose from but that means we don't rewrite the same method multiple times in multiple areas. We break the code apart into individual responsibilities so that we can reuse them in our application. If this wasn't needed, you could make them private and just test the main method but in this case the methods were valuable outside of just this one class.
Very good and well explained video. What I am a bit confused about is whenever you test which parameter is failing. Why is it a string? How can the compiler know what you're referring to? For instance, at 1:33:20 why is the parameter referred to as the string "FirstName" instead of Person.FirstName ?
That's what the exception takes in. It then converts it to the correct parameter via reflection. It makes it easier as an input, since it doesn't know what type it was otherwise.
Hey Tim! What do you think about Rider from Jetbrains? I have a student license and can't decide between Visual Studio and Rider ... Im used to both from work, so that won't be an issue :)
A good idea should be talk about "Integration Tests" (Facade => Service => DB, no mocking). Useful when you use "Dapper" (but not only) where you can do a typo easily.
Yeah, some more advanced, real-world examples of unit testing are on the roadmap. The whole idea of mocking, stubs, fakes, and all the rest are in there too.
Hi Tim, For the refactoring of your two thrown exceptions for FirstName and LastName, I came up with this and have all tests passing: public static void AddPersonToPeopleList(List people, PersonModel person) { CheckWhiteSpace(person.FirstName, "FirstName"); CheckWhiteSpace(person.LastName, "LastName"); people.Add(person); } public static void CheckWhiteSpace(string name, string paramName) { if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentException("You passed in an invalid parameter", paramName); } } However I'm unsure as to whether I would then have to create unit tests for the new method I have created, which essentially is already being tested in the sense that I know it throws an exception due to the tests on the method that calls it. Would love to hear your input, Cheers.
I would. It doesn't hurt and you have the opportunity to be more specific about the scenarios you check because the purpose of the new test is to test various "bad" strings vs testing adding a person to a list.
Trying to find a solution to testing React frontend, ASP dotnet Core backend. My ASP dotnet Core backend has a controller method that is connecting to an external api, but I want to make sure that my axios get request is connecting with said controller method. I'd begun the project by using one of VS2022's React + ASP dotnet Core templates.
FIX: Read& try this if you have problems getting the tests in the source code to run, although they show up in the test explorer: I kept getting errors like "no tests found in the DemoLibrary.Tests.dll" and it took me quite a while to figure this one out: The packages.config file in the DemoLIbrary.Tests shows that all the xunit packages are targeting net452, however all three projects in the solution target .NET Framework 4.6.1. Merely changing the targeted framework in the packages.config did not work for me, however this solved my problems: Open the NuGet package manager for the DemoLibrary.Tests project. Uninstall all xunit related packages in the correct order. Clean the solution. Then add xunit, xunit.runner.console and xunit.runner.visualstudio again. This time they will automatically target the correct .NET Framwork version and the tests should run fine.
Bingo - thanks. Was getting same error message so I did what you described. But now, I get a build error: "Metadata file '..\packages\xunit.analyzers.0.7.0\analyzers\dotnet\cs\xunit.analyzers.dll' could not be found". I restarted VS but to no avail. The packages.config shows xunit.analyzers version "0.10.0". And in my file directory, I see it as '..\packages\xunit.analyzers.0.10.0\analyzers ..." I wasn't sure how to get the app to remap to the new path, so I just renamed the folder to "xunit.analyzers.0.7.0". I know this is not the best fix, but works for now. If anyone knows how to get my app to properly remap to look in "xunit.analyzers.0.10.0" folder, let me know, thanks.
I'm late commenting but if I could give you the best programming youtube video award I would. This video was extremely helpful. Now for the bad news. I was wondering if you know of or have made a tutorial explaining how to get started unit testing a view model, I'm sure its going to be a lot of fun. I read somewhere that its just like testng a class, but I need to test that my properties are changing correctly etc. Thanks !
Excellent video! I like that xUnit Theories allow me to test multiple inputs with the same code, thereby lowering my test code to real code ratio (one of my fears with unit testing). Also, as a tip for others, in my methods for Theories, I prefer for the expected value to be the first parameter (as opposed to last) to handle methods I'm going to test that accept a variable number of parameters via the params keyword. For example, if I were going to test the String.Format method, I would like for my test method to have a signature like: public static void Format_Theory(string expected, string format, params object[] args) You can't really do it any other good way that I know. This way my unit tests will be consistent in terms of where the expected argument is going to be in the signature.
1:34:18 There's nothing wrong with copy / paste IF (and ONLY if) you are extremely regimented and always force your eyes to look over every letter of the pasted code (as if you're typing it for the first time) to check for any errors. I also force myself to think carefully that I have not made any wrong assumptions about the intent of my pasted code. By strictly following these two rules, I virtually never run into any issues despite copy / pasting all the time.
I would say a best practice is to avoid copy/paste and, if it makes sense, go through it like you are suggesting. Like you said, even with all of that careful work, it can still be a problem. It's just something to be aware of as a danger.
Great video Tim, as always. Thoroughly enjoyed it. I do have a couple of quick questions though. 1) If we're to test non static methods in non static classes should we instantiate those classes inside our test methods? 2) I didn't quite understand your take on 'Don't test private methods'... If we have private encapsulated methods that don't need to be exposed to clients should we just test the calling method which then calls those private methods and consider it done or is there another way? Also, if we don't need to test private methods and we are only concerned with ins and outs of public ones, why should we break public methods into many 'SRP' separate ones? Why dont we just leave their functionality inside public method?
1) Yes, instantiate those methods in the test method or inside of a helper method in your test class. 2) There is a difference between what you test and how you set things up for optimal development. You don't test private methods because you are testing external units of work. Internally, we use SRP to help us better organize our code, stay DRY, and improve maintainability. This isn't affected by our testing mechanism (or even if we test at all).
Think of the private methods as an implementation detail. They don't matter. You're testing the public interface plain and simple. You can't have SRP internally lol. SRP is more of a project level principle that is about people, not code. SoC is probably what Tim was reaching for. Don't conflate the two.
"The way you get good at something is not by watching videos. The way you get good at something is by doing it." - Tim Corey Yes. Thank you. Exactly. ✅✅✅✅✅ out of ☑☑☑☑☑ Perfect score.
( 28:50 ) I'm using Visual Studio 2019 community edition, and my tests already had their names in the test editor shortened by default (without having to add the json file "xunit.runner.json"). Is this an added feature of the latest version of xunit or VS?
I've returned to this video after a year and want to quickly refresh my knowledge, so it would be great for such cases to have a text variant of this lesson so I can do it in 10-20 minutes instead of hours. Do you consider to have such an option?
Hi Corey! Your videos are just...GREAT! LOVE THEM ALL! Just a simple question: is it necessary to build the solution each time you wanna run a test case? In my case it does not throws an error if I do not build the solution once again, but I would like to know in which case that may happen.
Tim, I miss the old way of coding where it is a lot cleaner, not much of hidden Freebies, anyway, this is the best ever simple coding on how to properly use XUnit. I hope you would also teach about MSTest in CI/CD on how it differs to XUnit Tests. Super THANK YOU Sir!
Enjoying your video! Thank you! Apologies if you explained this, I'm only a few minutes in... was wondering why it was so important to start the xUnit project off as a .NET Framework and not a .NET Standard library?
Couple reasons First, .NET Standard has some limitations that the .NET Framework does not. Second, it makes it easier to follow along if you use the same type as I do.
Dear Tim, I Have visual studio 2019 enterprise but these signs for test coverage not appear in my classes. So, would you please let me know how to make them appear or if you have any article I can follow to enable them. Thanks for your effort
Hi Tim, I really appreciate your work and hope to get a little update on TDD. Do you use the xUnit template for new projects? And can you give a hint, when to create a new Solution? Right now I am struggling whether I should put everything in one Solution or split the UI into a new one.
Thank you very much Corey for your video series. Your video is really amazing and I enjoyed so so much. However, at the video 1:25:00 when you said about parsing people to the AddPersonToPeopleList(people, newPerson). You said it is referring to the same 'house' of the address. I don't think that is correct since the method parameters does not use (ref keyword), then it will parse value (which is a value copy of people) instead of the reference. Could you please let me know if I am wrong or c# is different than Java. Thank you very much.
The statement I made is correct. A class instance is a reference type, meaning you only store the reference to the object, not a copy of the object (I'm simplifying but this is generally how it works). We only need to use the ref for value types that need to be passed like reference types. We have no choice but to pass reference types as references. Copying an object is actually a somewhat complicated endeavor.
I like that you don't edit out the times where things don't work as expected. It's actually helpful.
Excellent. Part of it is just wanting everyone to relax and not think you have to be perfect (I'm sure not). Part of it is that I do think it shows a realistic view on what I do as a developer. I am glad it is helpful to you.
I never used my eraser in math or physics exercises for this very reason :).
Totally agree. Thanks for making mistakes LOL
Completely agree! seeing what did not work is useful, so whoever is watching this video can learn from it
0:00 - Intro
1:37 - Working environment
3:35 - Demo application walk-through
7:14 - Unit Testing explained
9:45 - Creating a Unit Test project
13:22 - Setting up a test
22:37 - A bad Unit Test and Test Driven Development
25:48 - Opinion on Unit Testing
28:40 - Shortening Test name
31:08 - "Theory": Test method parameters and arguments
36:09 - Testing edge cases
38:43 - Testing number division
43:13 - Dividing by zero
48:55 - Testing methods that can throw exceptions: method returns output
54:14 - Debugging the Unit Test
55:19 - Testing the exceptions: method throws exception
59:22 - Testing the exceptions: method argument throws exception
1:05:07 - Testing methods that do more than one thing: what is a Unit of work?
1:10:56 - Breaking method in to individual methods, what to test and what not to test
1:18:50 - "Add to List" Tests: working test
1:26:50 - "Add to List" Tests: failing test
1:35:37 - Homework
1:40:05 - Concluding remarks
Greatly appreciated by myself and the other students.
"the way you get good at something is to not watch videos, but by doing it!" - so true!
Yep.
This was a truly great video. Not only was the educational content about the specific subject matter of unit testing fantastic, but also, just taking the time to carefully convey the fundamentals serves to remind us all that development and engineering is not about just quickly getting through things, but that it is about long term excellence and profound understanding.
I am glad you found it so helpful.
Thank you for this one, as well! One note, being 5 years later, adding the project as xUnit Test Project, allows for selection of newer .NET versions. Using the Class Library (.NET Framework), doesn't allow going beyond .NET v4.x. Which slightly changes how to add the project references from Dependencies>right click>Add Project Reference.
Thanks for sharing!
This is how you make a tutorial! All of them all greate. I was like test code cost me more time but now I see the benefits and expecialy how you show it in this tutorial
Excellent!
your videos are great tim and you have such a likeable personality, it feels like a friend is teaching me
Thanks!
The best explanation and the most detailed for free accessible video about this topic. You are really the man!
Glad you enjoyed it!
This one is like attending a psychologist, thank you so much, I've been programming more than 10 years but learned about testing only recently, same with design patterns, all because I usually programmed alone and never cared about what others are doing, but now I feel like incompetent which hinders me even at employment, though I decided to go through all your learning path videos and fix this ))
Thank you!
Glad it was helpful!
This a best tutoreal about unit testing what i have seen, plz add more and more videos about this !!! Thank you so much.
Thank you. I have noted this to Tim's ideas for possible future topics.
I might have to subscribe to Tim Corey... (jk - I already did). This course is, what, 4 years old and yet, it's still applicable today. Easily, one of the best intros to unit testing I've ever seen. Thanks for posting this!
You are welcome.
Opinion on Unit Testing is doooooooooope. Nice speech.
Thanks!
Always clear and organized. Appreciate your tutorials. Even your voice is soothing. THANK YOU!
Glad you like them!
Hi Tim. Thanks for the great tutorial (and the follow up Moq video). I've always grumbled about testing, but this has opened my eyes to see that it can really be super satisfying and fun. I've had lots of fun today extending your sample project with tests for the CSV serialize/deserialize and theories around handling bad input etc. All round top notch stuff, thanks mate!
Thank you!
@@IAmTimCorey Also, I agree 100% w/ your philosophy on the testing fanatics. They have definitely deterred me from getting into Unit Testing in the past. Thanks for the help.
As always you are at the top of the art of presentation!!!
Thank you!
Tim, your words about TDD fanatics is really important. I (and I guess lot of us) feel I'm not good enough because I haven't written lot of tests in my career.
That's brings some guilt for me.
You say 10 is better than 0, 11 is better than 10. That sentence give me a hope and ability to stay calmly focus and slowly building my skills in tests area.
Thanks you Tim!
Just be sure tests you write add value. No one needs redundant tests that take up time and resources.
wow. recently started a new job and was a bit overwhelmed with the unit testing and mocks but found this video extremely helpful. I feel a little more confident about them now. Thank you so much! subscribed :)
Awesome!
This video not just covers unit testing but also the way we extract and extract and extract following Single Responsibility Principle and Clean Code. Thank tou Tim Corey
Tim tries to incorporate real world insights. Sounds like it was helpful. Thanks for watching.
Thanks Tim. Again! You explained material in more depth (for free) than paid course in Udemy I took.
You are welcome.
Thank you very much! By watching your video I now understand Unit testing so much better. Keep up the good work.
Awesome!
Thanks for the detailed walkthrough! A question, what if I just want to check whether an exception is thrown, and don't care about the exception type? Asset.Throws seems to work with the specific type only.
Check for the type of Exception. Since all exceptions derive from Exception, that should give you what you need.
Back in '93 when I started my programming career, we built our requirements using Test Cases. Then we built the code using the Test Cases. Later, when Test script tools came along, Test Data was stored separately and 'pulled' into the test script. It allowed for a much easier and larger test bed.
It's true as you said, you can go overboard with your testing. I basically test upper and lower bounds, test data types, test Nulls, and finally test real--life scenarios (using recorded scripts).
Thanks for sharing.
Thanks for the insight Tim. You set the benchmark, here and all your other videos I've watched.
Glad you like them!
Hi Tim, I would like to thank you, Your Videos was very useful for me, I mean not only this tutorial but also almost every videos i watched until now. Thanks again🙏
You are welcome.
Thankyou for this video. I have implemented most of the concepts taught here in my company's code.
Excellent!
I recectly was put to work in doing some small projects and testing them in my company where I work as a student worker. They used XUnit, Moq, and Autofixture, and this video is definetly a good start to build upon. Once done, I need to watch something in Moq and Autofixture, but this really makes things easier :)
I’m glad!
Tim Corey you have done an excellent job. Thank you very much. Hopefully I will pass the coding interview assessment I am about to do
Best wishes.
great tutorial. Very easy to understand having done no unit testing up until this point
Glad it was easy to understand. Going to start doing unit testing now?
This is super cool and well explained. Thanks so much..
You are welcome.
Blimey! You got up early in the morning to do this video.
Actually I stayed up late. My window to record (when the house is quiet since I don't have a dedicated soundproof studio) is between 10pm and whenever I'm done. Usually that means midnight or 1am but sometimes it goes longer.
WOW, Amazing video! This was really informative on how to create and execute XUnit tests!
Glad it was helpful!
This is very helpful and amazingly clear explained. Thank you.
You are welcome.
probs, i really like the way you explain stuff.
great work with the time stamps aswell
Thanks for watching and sharing your thoughts.
Great video, as always. I've worked with xUnit before but now I've learned a lot of xUnit, unit tests and best practices. Thank you for sharing your knowledge. I'm definitively going to practice it right away. =)
Thanks for growing your skills with this video.
He's recording it at 5 AM. respect!
I wonder some times if he really ever sleeps.
Thank you Tim! You make things look easy.
You are welcome.
Really enjoyed the way you described it, unlike lots of example with simple scenarios
Thank you
Thanks for watching. Please help get the word out about Tim!
@@tomthelestaff-iamtimcorey7597 For sure 👍
Great advice on testing! I agree, that it doesn't have to be all or nothing, even some tests can help you out a lot. I have a few tests for my ahk project, for stuff that I wanted to test while developing. It's like 2% code coverage, but those tests definitely help to make absolute sure *that* part of code works. If I didn't have them, it'd be 0% and that's obviously worse. Better to do a bit than no bit!
Thank you!
Great lesson! Thank you so much for sharing, Mr. Corey!
You are welcome.
Hi Tim, great video as always! :d
I have seen multiple videos where you hard coded the name of a property, so i think you missed a cool feature of c#, since c# 6, you can use the "nameof()" keyword to get the name of a type or member as string at compile time (ie. namof(Person.FirstName)) so the code will not break if you rename FirstName to something else.
There is a similar keyword called "typeof()", which you can use to get a compile time Type variable, and you can even use it on T types.
I believe this video (and I know quite a few others were as well) was done before C# 6 came out (or at least I wasn't using it yet). I did miss it on a few videos after it came out but I do use it now and love it! Thanks for bringing it up.
Tim, thank you for the best video. You explained very well.
You are welcome.
Great video Tim, first time I get into unit testing and I really like your slow / calmed pace of teaching, the pauses you make are key to be able to graps the concepts of what you're explaining. I will be doing the homework on this project now :)
I am glad you found it useful.
Great lesson. My only feedback is that it would be great if the provided source code was from the state of the VS Solution from the start rather than after you made the changes so we can learn by actually making those changes ourselves.
It would be great to have a tutorial on the subject of Unit tests VS Integration tests and how to use Dependency Injection to isolate units and convert Integration tests to Unit tests
Added to the list of suggestions, thanks
I Appreciate it, man. You are awesome.
Thank you!
Best tutorial on Unit Testing with Xunit. ❤
Glad you think so!
@@IAmTimCorey Sir, please can you make a tutorial on NHibernate?
Im currently studying to become a fullstack developer. Unfortunately, even though my teachers are very skilled and knowledgeable, they are somewhat lacking in the pedagogic.
Your videos are amazing complimentary to understand the fundamentals of subjects that I sometimes find hard to grasp.
Big thank you!
I am glad my content has been so helpful.
Thanks for putting this video up I'm trying to learn this and it's so hard to understand for me. Liked and subscribed.
I am glad the content has been helpful for you.
@@IAmTimCorey I have to keep rewatching until I get it. I tried testing some methods today and I couldn't figure out how to make the test pass. I am lost.
Thank you! This is exactly what makes this channel so great: 1:05:07
You are most welcome. Thanks for watching.
Thank you for sharing this course!
You are welcome.
It might look frightening and over the top to do unit testing in the early stage of your coding. But this is actually a time where testing have helped me in C# a lot. Like Tim says it forces you to write sensible and well structured code from the start. And it will also make it clearer for you on "what do next". It basically solves a lot of the uncertainty you always have bet a bit extra as a beginner.
And with the boosted confidence you will move forward faster. This is my belief.
Agreed.
It's called TDD :)
Hi Tim. Great video but I do have a question in relation to Test Driven Design. If you write the "test" first, this would mean in your test you would be calling a method which doesn't exist yet. So your test wouldn't fail... it wouldn't compile and run at all. So just for clarification, is the idea that you write the test... but put in something "hard coded" to represent a failure scenario. This get's you the red light as you put it. Then write the method, and swap the hard coded value for the method call in order to get the green light?
Create the method stub and then write the test. That way, the test fails but everything compiles. Usually if a method has a return, I add a "throw new NotImplementedException();" so that it does compile. That way, when you write the "real" code, the test will go from red to green.
This was amazing and far clearer and easier to understand than other videos which basically just cover an add method.
Would have like to see a fully fleshed out suite of tests for 1 method though. I'm curious if you would test things like if an argument was null etc even though it would normally be handled on the front end before it reaches the back end code for example.
I test the things that can happen. If there is no way for that to happen, I probably wouldn't test for it. Although, that's probably a rare case. Usually, I plan for that eventuality in my code so then I test for it.
59:10 why doesn't the general exception work? the specific exception is still an exception ... so why does it need to be specified?
Tremendously helpful! Thanks, Tim!
You are welcome.
Test Driven Development people? Hmm :-)
You really highlight the issues, in a nice way, why people do not use TDD, and this video is a fine example on why it makes sense to use unit testing and why TDD is a strong tool in development
Thank you!
Can you create a video about how to do integration testing? Do you just create a separate test project and use real external sources? Obviously they wouldn't be production they would be test systems that are backups of production.
Thanks for the suggestion. Please add it to the list on the suggestion site so others can vote on it as well: suggestions.iamtimcorey.com/
Great video - as always! You really help me learn to write much better code. Thank you so much! Will you show different forms of testing in upcoming videos (i.e. end to end testing or more advanced unit tests)? That would be really helpful!
Yes, I will be covering other testing types in future videos. First I want to cover more about unit testing though (mocking is the biggest area to cover yet).
I had not heard of that term before in this context - so I am looking forward to learn more...
The video was very helpful as usual, thank you!!
I'm looking forward to learning about mocking and perhaps also how to test private methods with XUnit (as I'm unsure all my smaller "helper methods" should be public just to make them easily testable.. That would go against my attempts at encapsulation. But I do want to test them.). I'm also looking forward to an intro to integration and end to end testing sometime in the future but I know you get a LOT of video requests.
Hello Tim is Test explore available in vs2019 comuinty
Yep
Yes
Hi IAMTimCorey, just wanted to ask you something about the part where you talk about not moking microsoft calls (File class in your example). So, In the case you have there where you add a person object to a list and then to file. If I understood correclty, you prefer to unit test the little bits not dependant of external things (like file system), and then test all the function (that contains the File call) in an integration test. Am I right? I like this idea because I also think that almost any method can be splitted and there would be parts really hard to unit test. Mainly external dependecies like DbContext or DBset, etc. The sensible thing to do here, is unit test what can be unit tested and then delegate the other stuff to an integration test. Do we agree?
Usually if you are following SRP and other good OOP principles, you can unit test just about everything. I don't go crazy with that theory but it does make you re-think how you write code when you are considering how to make it testable. Unit tests should test one unit (one specific thing). Then, you can test the interaction of things together in an integration test, so yes, I think we agree.
Hi Tim, been following you for a couple of weeks by now and I'd like to leave a couple of notes based on experience. Following a TDD approach I'd have written the test first for the DataAccess class instead of refactoring because (supposing it's a real life situation where your DataAccess is actually working) you wouldn't be sure if your class continued to work after the refactoring.
The other thing is that your testing approach would only work with classes that are more structured-oriented or functional-oriented than object-oriented (for example, classes with lots of public methods that are either static or don't keep instance attributes). In real object-oriented unit testing the smallest unit of code to test is not a single method but the class as a whole calling the minimum amount of methods required for the class to work (for example in a BankAccount class the minimum unit testing could be create the account, deposit a small amount of money, request the balance, withdraw the money and close the account). This is a mistake done by many (if not most) programmers wanting to start unit testing and also TDD supporters. And no, I'm not one of those mad zealots :) but if you test only a method in a class that had 5 instance attributes you will virtually skip every state where the attribute work for your tested method but breaks every other method.
Best regards
I tried not to go down the TDD road because if you are just learning unit testing, you probably have existing code that needs to be tested. As for the working with classes instead of methods, this sounds more like integration testing than unit testing. You can test the individual methods and just identify the various inputs and outputs where a changed value occurs and then test to those values.
Really helpfull and great course! Thanks Tim Corey!
You are welcome.
Thanks for the video! I'm just starting to get my feet wet with unit testing after a couple years of programming. I've been running into situations where I've changed code and things break. My applications are complex enough where it would be quite a pain to try and manually test for possible errors. It's also rather difficult to think of every possible thing that can go wrong when I make a change. It's nice to build tests that continue to run automatically as the application is built so that I don't have a growing list of things to check for before I deploy updates.
One small thing I've noticed in your videos is that there is a slight delay between the video and the audio. I'll see the cursor (blinky text editing thing) move on your screen then about half a second later I'll hear a mouse click. It would nice if the audio was perfectly in sync with the video. It's slightly distracting, but not a huge deal. Great videos though. Probably the best on the internet for learning code as far as I'm concerned.
I've noticed that issue and corrected going forward (mostly). There is a bug in the software I use to record that sometimes allows it to get out of sync. I haven't tracked down why yet and it only happens occasionally now but I try to fix it when I catch it in time.
Question: At 45:45, where you get an error on your Divide_DivideByZero test, my test passes without error. I've searched, but can't find if this "divide by zero" error no longer applies in VS19? Does anyone know? I've triple checked and my code is the same as in the video.
Cheers
A great video for introduction to unit test, Thanks!
Glad it was helpful!
I have a question regarding the breaking bigger method to bunch of separted methods (Around 1:10:00 ) . Doesn't it create dozens of public methods that make this class ridicolous in use (lots of methods to choose from when only part of the are really necessary) ?
Breaking a big method into smaller methods helps us accomplish SRP ( th-cam.com/video/5RwhyZnVRS8/w-d-xo.html ). It does mean we have more options to choose from but that means we don't rewrite the same method multiple times in multiple areas. We break the code apart into individual responsibilities so that we can reuse them in our application. If this wasn't needed, you could make them private and just test the main method but in this case the methods were valuable outside of just this one class.
Awesome tutorial Tim. Thanks for providing this video.
You are most welcome. Thanks for watching.
Very good and well explained video.
What I am a bit confused about is whenever you test which parameter is failing. Why is it a string? How can the compiler know what you're referring to? For instance, at 1:33:20 why is the parameter referred to as the string "FirstName" instead of Person.FirstName ?
That's what the exception takes in. It then converts it to the correct parameter via reflection. It makes it easier as an input, since it doesn't know what type it was otherwise.
Hey Tim!
What do you think about Rider from Jetbrains?
I have a student license and can't decide between Visual Studio and Rider ...
Im used to both from work, so that won't be an issue :)
I haven't used Rider (yet) so I'm not a good judge of the comparison. I just know there isn't much I feel is missing from VS (for free).
Really helpful to get going. Thanks for your efforts and attention to important details.
You are most welcome. Thanks for watching.
A good idea should be talk about "Integration Tests" (Facade => Service => DB, no mocking). Useful when you use "Dapper" (but not only) where you can do a typo easily.
Yeah, some more advanced, real-world examples of unit testing are on the roadmap. The whole idea of mocking, stubs, fakes, and all the rest are in there too.
Great intro to unit testing. Thank you.
Glad you liked it!
I was waiting for this video a long time! :D
It has been a long time in coming. I wanted to get it right.
Hi Tim,
For the refactoring of your two thrown exceptions for FirstName and LastName, I came up with this and have all tests passing:
public static void AddPersonToPeopleList(List people, PersonModel person)
{
CheckWhiteSpace(person.FirstName, "FirstName");
CheckWhiteSpace(person.LastName, "LastName");
people.Add(person);
}
public static void CheckWhiteSpace(string name, string paramName) {
if (string.IsNullOrWhiteSpace(name)) {
throw new ArgumentException("You passed in an invalid parameter", paramName);
}
}
However I'm unsure as to whether I would then have to create unit tests for the new method I have created, which essentially is already being tested in the sense that I know it throws an exception due to the tests on the method that calls it. Would love to hear your input, Cheers.
I would. It doesn't hurt and you have the opportunity to be more specific about the scenarios you check because the purpose of the new test is to test various "bad" strings vs testing adding a person to a list.
@@IAmTimCorey Thanks Tim! Your videos are amazing by the way :)
Trying to find a solution to testing React frontend, ASP dotnet Core backend. My ASP dotnet Core backend has a controller method that is connecting to an external api, but I want to make sure that my axios get request is connecting with said controller method. I'd begun the project by using one of VS2022's React + ASP dotnet Core templates.
FIX: Read& try this if you have problems getting the tests in the source code to run, although they show up in the test explorer:
I kept getting errors like "no tests found in the DemoLibrary.Tests.dll" and it took me quite a while to figure this one out:
The packages.config file in the DemoLIbrary.Tests shows that all the xunit packages are targeting net452, however all three projects in the solution target .NET Framework 4.6.1.
Merely changing the targeted framework in the packages.config did not work for me, however this solved my problems:
Open the NuGet package manager for the DemoLibrary.Tests project. Uninstall all xunit related packages in the correct order. Clean the solution. Then add xunit, xunit.runner.console and xunit.runner.visualstudio again. This time they will automatically target the correct .NET Framwork version and the tests should run fine.
Thanks for sharing!
Bingo - thanks. Was getting same error message so I did what you described. But now, I get a build error: "Metadata file '..\packages\xunit.analyzers.0.7.0\analyzers\dotnet\cs\xunit.analyzers.dll' could not be found".
I restarted VS but to no avail. The packages.config shows xunit.analyzers version "0.10.0". And in my file directory, I see it as '..\packages\xunit.analyzers.0.10.0\analyzers ..."
I wasn't sure how to get the app to remap to the new path, so I just renamed the folder to "xunit.analyzers.0.7.0". I know this is not the best fix, but works for now. If anyone knows how to get my app to properly remap to look in "xunit.analyzers.0.10.0" folder, let me know, thanks.
Thank you for sharing asyncawake. This solved me problem.
I'm late commenting but if I could give you the best programming youtube video award I would. This video was extremely helpful. Now for the bad news. I was wondering if you know of or have made a tutorial explaining how to get started unit testing a view model, I'm sure its going to be a lot of fun. I read somewhere that its just like testng a class, but I need to test that my properties are changing correctly etc. Thanks !
Thank you!
42:30 This is a good example of how your code can verify your unit tests.
Excellent video! I like that xUnit Theories allow me to test multiple inputs with the same code, thereby lowering my test code to real code ratio (one of my fears with unit testing).
Also, as a tip for others, in my methods for Theories, I prefer for the expected value to be the first parameter (as opposed to last) to handle methods I'm going to test that accept a variable number of parameters via the params keyword.
For example, if I were going to test the String.Format method, I would like for my test method to have a signature like:
public static void Format_Theory(string expected, string format, params object[] args)
You can't really do it any other good way that I know.
This way my unit tests will be consistent in terms of where the expected argument is going to be in the signature.
Glad you are enjoying the theories.
Really helpful video. Cleared my TDD concepts! :)
Great!
1:34:18 There's nothing wrong with copy / paste IF (and ONLY if) you are extremely regimented and always force your eyes to look over every letter of the pasted code (as if you're typing it for the first time) to check for any errors. I also force myself to think carefully that I have not made any wrong assumptions about the intent of my pasted code. By strictly following these two rules, I virtually never run into any issues despite copy / pasting all the time.
I would say a best practice is to avoid copy/paste and, if it makes sense, go through it like you are suggesting. Like you said, even with all of that careful work, it can still be a problem. It's just something to be aware of as a danger.
Great video Tim, as always. Thoroughly enjoyed it. I do have a couple of quick questions though.
1) If we're to test non static methods in non static classes should we instantiate those classes inside our test methods?
2) I didn't quite understand your take on 'Don't test private methods'... If we have private encapsulated methods that don't need to be exposed to clients should we just test the calling method which then calls those private methods and consider it done or is there another way? Also, if we don't need to test private methods and we are only concerned with ins and outs of public ones, why should we break public methods into many 'SRP' separate ones? Why dont we just leave their functionality inside public method?
1) Yes, instantiate those methods in the test method or inside of a helper method in your test class.
2) There is a difference between what you test and how you set things up for optimal development. You don't test private methods because you are testing external units of work. Internally, we use SRP to help us better organize our code, stay DRY, and improve maintainability. This isn't affected by our testing mechanism (or even if we test at all).
Think of the private methods as an implementation detail. They don't matter. You're testing the public interface plain and simple. You can't have SRP internally lol. SRP is more of a project level principle that is about people, not code. SoC is probably what Tim was reaching for. Don't conflate the two.
If my project is written in .net core should I add a .net core class library for my tests?
Yes
"The way you get good at something is not by watching videos. The way you get good at something is by doing it." - Tim Corey
Yes. Thank you. Exactly.
✅✅✅✅✅ out of ☑☑☑☑☑
Perfect score.
Thank you!
great video, just what I needed.
Glad it helped!
Great video sir. Thank you so much for making our life easy.
You are welcome.
Great tutorial, thanks Tim!
You are welcome.
( 28:50 ) I'm using Visual Studio 2019 community edition, and my tests already had their names in the test editor shortened by default (without having to add the json file "xunit.runner.json"). Is this an added feature of the latest version of xunit or VS?
I believe it is a newer feature of Visual Studio, yes.
I've returned to this video after a year and want to quickly refresh my knowledge, so it would be great for such cases to have a text variant of this lesson so I can do it in 10-20 minutes instead of hours. Do you consider to have such an option?
Thanks Tim, you the best!
You are welcome.
Hi Corey! Your videos are just...GREAT! LOVE THEM ALL! Just a simple question: is it necessary to build the solution each time you wanna run a test case? In my case it does not throws an error if I do not build the solution once again, but I would like to know in which case that may happen.
You only need to do a rebuild if the code has changed.
Tim, I miss the old way of coding where it is a lot cleaner, not much of hidden Freebies, anyway, this is the best ever simple coding on how to properly use XUnit. I hope you would also teach about MSTest in CI/CD on how it differs to XUnit Tests. Super THANK YOU Sir!
Not sure what you mean by "hidden freebies", but I am glad you enjoyed the video.
this is pure gold
Thanks!
Thanks for the video Tim!
You bet!
Enjoying your video! Thank you! Apologies if you explained this, I'm only a few minutes in... was wondering why it was so important to start the xUnit project off as a .NET Framework and not a .NET Standard library?
Couple reasons First, .NET Standard has some limitations that the .NET Framework does not. Second, it makes it easier to follow along if you use the same type as I do.
Dear Tim,
I Have visual studio 2019 enterprise but these signs for test coverage not appear in my classes. So, would you please let me know how to make them appear or if you have any article I can follow to enable them.
Thanks for your effort
Under the Test menu, go to Live Unit Testing and start it.
@@IAmTimCorey Thanks
My professional project uses NUnit. Is it worth to watch and learn XUnit instead of NUnit? Is there any plans on making a video about NUnit?
No need. They are really close. It is more about preference. Not sure about an nUnit video. Maybe.
Hi Tim, I really appreciate your work and hope to get a little update on TDD. Do you use the xUnit template for new projects? And can you give a hint, when to create a new Solution? Right now I am struggling whether I should put everything in one Solution or split the UI into a new one.
45:45 you can use: double expected = double.PositiveInfinity;
Thanks for the tip.
Thank you very much Corey for your video series. Your video is really amazing and I enjoyed so so much. However, at the video 1:25:00 when you said about parsing people to the AddPersonToPeopleList(people, newPerson). You said it is referring to the same 'house' of the address. I don't think that is correct since the method parameters does not use (ref keyword), then it will parse value (which is a value copy of people) instead of the reference. Could you please let me know if I am wrong or c# is different than Java. Thank you very much.
The statement I made is correct. A class instance is a reference type, meaning you only store the reference to the object, not a copy of the object (I'm simplifying but this is generally how it works). We only need to use the ref for value types that need to be passed like reference types. We have no choice but to pass reference types as references. Copying an object is actually a somewhat complicated endeavor.