Learn Unit Testing with NUnit and C# | Elias Spock | Skillshare

Learn Unit Testing with NUnit and C#

Elias Spock, Chance favors the prepared mind.

Learn Unit Testing with NUnit and C#

Elias Spock, Chance favors the prepared mind.

Play Speed
  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x
51 Lessons (3h 40m)
    • 1. 00 Promo

    • 2. 01 Outline

    • 3. 02 What is a Unit Test

    • 4. 03 Unit Testing Frameworks

    • 5. 04 Your First Unit Test

    • 6. 05 Naming Conventions

    • 7. 06 Running and Debugging Unit Tests

    • 8. 07 Benefits of Unit Testing

    • 9. 08 Who Should Write Unit Tests and When

    • 10. 09 Programmer's Oath

    • 11. 10 Conclusion

    • 12. 01 Outline

    • 13. 02 Assert Intro

    • 14. 03 Assert Demo

    • 15. 04 Arrange Act Assert

    • 16. 05 Running Tests from the Console

    • 17. 06 SetUp and TearDown

    • 18. 07 OneTimeSetUp and OneTimeTearDown

    • 19. 08 Parameterized Unit Tests

    • 20. 09 Grouping and Ignoring Unit Tests

    • 21. 10 Code Coverage

    • 22. 11 Conclusion

    • 23. 01 Outline

    • 24. 02 Demo of a Testing Problem

    • 25. 03 Refactoring to Make Code Testable

    • 26. 04 Test Doubles

    • 27. 05 Hand Rolled or Manual Test Doubles

    • 28. 07 Problems with Manual Test Doubles

    • 29. 08 Mocking Frameworks

    • 30. 09 Writing Unit Tests with a Mocking Framework

    • 31. 10 NSubstitute Mocking Framework

    • 32. 11 Detroit School vs London School of Unit Testing

    • 33. 12 Conclusion

    • 34. 01 Outline

    • 35. 02 What is TDD

    • 36. 03 Red Green Refactor

    • 37. 04 TDD and Design Upfront

    • 38. 06 Conclusion

    • 39. 01 Outline

    • 40. 02 Do Unit Tests Guarantee the Success

    • 41. 03 Pragmatic Unit Testing

    • 42. 04 Integration Tests

    • 43. 05 Singletons and Static Classes

    • 44. 06 Header Interfaces

    • 45. 07 Demo of Refactoring to a Testable Design

    • 46. 08 How Much Test Coverage is Enough

    • 47. 09 Testing Trivial Code

    • 48. 10 The Rule of Testing a Single Concern

    • 49. 11 More on Best Practices

    • 50. 12 Generating Unit Test Method Signatures

    • 51. 13 Conclusion

  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels
  • Beg/Int level
  • Int/Adv level

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.





About This Class

Learn deeply the concepts and tools that you will need to build maintainable and reliable software.

Teaching Approach

No fluff, no ranting, no beating the air. I esteem your time. The course material is succinct, yet comprehensive. All important concepts are covered. Particularly important topics are covered in-depth. For absolute beginners, I offer my help on Skype absolutely free, if requested.

Take this course, and you will be satisfied.

Build a solid foundation in Unit Testing with this course

This course is all about writing effective unit tests using C# programming language and NUnit as a unit testing framework. Along the way, we will learn the concepts related to unit testing. Today unit testing is an absolutely required skill from any professional developer. Companies expect from developers to know how to write unit tests including all the most important topics such as mocking and test driven development (TDD in short). This course does not cover all the features of NUnit. This course is way more interesting.

Learning unit testing puts a powerful and very useful tool at your fingertips. Being familiar with unit testing you can write reliable and maintainable applications. It is very hard to lead a project which is not covered by unit tests.

Content and Overview

This course is primarily aimed at beginner developers. It provides solid theoretical base reinforced by tons of practical material.

We start with basics of unit testing. What is a unit test? What unit testing frameworks exist? How to run and debug unit tests. After getting acquainted with the basics, we will get to the NUnit framework. Here you’ll learn how to install the framework, set the runner. Then you’ll learn the basics of assertions and arrange-act-assert triplet. Other key features of NUnit are also covered:

  • Running tests from the console
  • Setup and teardown unit tests
  • Parameterized tests
  • Grouping and ignoring

Practicing writing of unit tests, it’s impossible to avoid applying mocks. I like the word “test double” more, in general. By the way, you’ll learn what the difference between the following notion is:

  • Test double
  • Fake
  • Dummy
  • Stub
  • Mock

You’ll learn how to write test doubles manually. You will also see a simple example of how to use a mocking framework for using mocks. I’ll use NSubstitute mocking framework for demonstration.

At the end of this section, you’ll get acquainted with two key approaches to unit testing, Classic or Detroit School and London School of unit testing.

You’ll separately learn the basic of test-driven development. It is hard to imagine a modern professional developer who doesn’t know about TDD, so you’ll learn what it is and what it is about. You’ll see the Red-Green-Refactor triplet in action.

I could not complete the course avoiding the best practices of writing unit tests. You’ll learn the basic concepts of the modern approach to unit testing called “pragmatic unit testing”. You’ll see what problems static classes and singletons bring regarding the unit testing. They make code harder to unit test. After that, you’ll learn the problem of extracting interfaces just for the sake of introducing shims for injecting dependencies.

You’ll know should you write unit tests for the trivial code. You’ll learn a lot more in the course.

So, in short, the course covers the following topics:

  • Basic notions of Unit Testing
  • NUnit and its basic features
  • Test Doubles including fakes, dummies, stubs, spies and mocks
  • How to write manual test doubles and how to use a mocking framework
  • TDD, red-green-refactor triplet
  • A great number of best practices of writing unit tests

In the end, we will recap what you have learned, and you will try to understand where you have to go further with the intention to master your skills.

How long is this course: The course is around 4 hours. All are video lectures. You will be able to download all the slides and code samples used in the course.


Keywords related to the course:

  • Visual Studio unit testing tutorial
  • NUnit unit testing tutorial
  • Dot Net testing framework
  • C# unit test framework
  • Visual Studio unit testing framework tutorial
  • csharp unit testing tutorial TDD in C#
  • NSubstitute
  • TDD
  • Test Driven Development
  • unit testing C#

Meet Your Teacher

Teacher Profile Image

Elias Spock

Chance favors the prepared mind.


I'm thankful enough for that I love what I do.
I began my career as a postgraduate student participating in Microsoft ImagineCup contest.
I've been working with .NET platform since 2003. I've been professionally architecting and implementing software for nearly 7 years, primarily based on the .NET platform. I'm passionate about building rich and powerful applications using modern technologies. 
I'm a certified specialist in Windows Applications and Service Communication Applications by Microsoft.
I'm one of the coordinators of the MSK.NET User Group in Moscow.

"If it's work, we try to do less. If it's art, we try to do more." - Seth Godin.

What I can say is that software is my art.

See full profile

Class Ratings

Expectations Met?
  • Exceeded!
  • Yes
  • Somewhat
  • Not really
Reviews Archive

In October 2018, we updated our review system to improve the way we collect feedback. Below are the reviews written before that update.

Your creative journey starts here.

  • Unlimited access to every class
  • Supportive online creative community
  • Learn offline with Skillshare’s app

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.


1. 00 Promo: Hi. Welcome to the course. Learned union Fasting with Union Fancy shop. I'm the last of a K engineer spark from engineer sparked dot com, and I'll be leading you through the course. I began my career as a postgraduate student participating in Microsoft. Um, Agent Cop contest I've been working with Don't Left Platform Since 2003 I've been professionally architect and implementing. Suffered for nearly seven years primer and based on Don't Let Black. I am passionate about building the rich and powerful applications using modern technologies . I'm a certified specialist in Windows applications and service communication applications by Microsoft. And here is my teaching approach. No fluff, no ranging. No beating the air. I wasting your time with course material is 16. A gap comprehends All important concepts covered particularly important. Topics are covered in depth for absolute beginners. I offer my help on Skype absolutely free if requested. Take this course and you'll be satisfied today. Union testing is the absolutely required skill which is required from any professional developer. Companies expect from developers to know how to write unit tests, including all the most important topics such a smoking and test driven development. Dee Dee Dee Ensure. But this course is all about writing effective unit tests using C sharp programming language and an unit s a unit testing framework. Along the way, we will learn the concepts related to unit testing They scores. Doesn't cover all the features, often unit. This course is way more interesting. Learning unit testing puts a powerful and very useful to at your fingertips. Being familiar with the unit testing. You can write reliable and maintainable applications. It is very hard to lead a project, which is not covered by union nests. This course is primarily aimed at beginner developers, and some experience in C shop programming is required if the scores provides solar theoretical base reinforced by tones of practical material. We start with basics off unit testing. What is a unit test? What unit testing frameworks exist? How to run in the park unit tests? After getting acquainted with the basics, we'll get to the unit framer. Here you learn how to install the framework and set up their honor. Then you learn the basics of assertions and arrange act certain triplet. Other key features of one unit viral sub coward go to run tests from the console set up and tear down unit tests, very meter, eyes, tests and grouping and ignoring and other features practicing writing off unit tests. It's impossible to avoid applying marks. I like. The work does double more in general, by the way you learn. What is the difference between the falling notions? Just double fake Tommy? Stop. No, you learn how to write does doubles manual. You also see a simple example of how to use and marking framework for using marks. I'll use and substitute marking frame for demonstration at the end of the section dedicated to Marx. You'll get acquainted with two key approaches to unit testing Classic for Detroit School and London School Off unit Testing. You'll separately learn the basics of test driven development. It is hard to imagine a modern professional developer who doesn't know about TDD, so you learn what it is and what it is about. You'll see the red green factor treatment in action. I couldn't complete the course, avoiding the best practices and writing unit tests. You learn the basic concepts of the modern approach to unit testing called pragmatic union testing. You'll see what problems stated classes and Singleton's bring regarding the unit plastic. They make goat harder to union test. After that, you'll learn the problem off extracting interfaces just for the sake of introducing machines for injecting dependencies. You will know, should you write unit tests for trivial code, you learn a lot more in this course. So in shirt, the course covers the following topics. Basic notions, Off unit testing and unit and its basic features does doubles, including fakes. Dominic stops spies and marks, how to write manual test doubles and how to use a marking frame. De de de red green red factor treatment and a great number of best practices are writing unit tests. In the end, we will recap what you have learned, and you try to understand where you have to go further with the intention to master your skills. I'll be glad to see you in the course. Enroll and stopped learning the unit testing within union and see shop 2. 01 Outline: Hi. This is allies for full of a K engineer Spark from engineers park dot com, and we continue our tour on the unit testing. In this section, you'll learn. What guarantees does unit testing provide? What is the pragmatic unit testing? How Singleton's and stated classes harm the unit, testing the problems related to extracting interfaces just for the sake of dependency injection? How much discovery is enough? The problem off testing three Ville code. What really means the rule off a single concern? Testing in a single unit test In the next lecture, we will start from an interesting question. Do unit tests guarantee the success? 3. 02 What is a Unit Test: the unit testing concept was introduced somewhere in the 19 seventies. Decades have passed. Unit tests are still alive. That's because of their great importance in the field off software development. Count back. Remember this name if you didn't know it, introduced unit tests in small talk with the first object oriented language. I don't want to dig the history, so let's get started with a simple definition off a unit test. A unit test is a function which calls another function unit and checks the correctness off the outcome from the cold function. If the outcome is incorrect or another word unexpected, then the unit test fails. If the outcome is correct or expected, then the unit test passes. Another important definition is the definition off. A system under test or sought in short units are usually contained within classes, so we usually write many unit tests for a single class. Such a class we call SAT or system under test. In the beginning, I also want to give you a definition often integration testing, since I want you to understand the difference between these two absolutely different concepts, I like the definition from the book off. Roy Osheroff the art off unit testing with examples in C shop integration Testing is testing a unit off work without having full control over all of it and using one or more off its aerial dependencies, such as time network database threats, random number generators and so on. So the main difference between unit tests and integration tests is that unit tests isolate units they test isolate, for example, from working with networks or date basis. At the same time, integration tests just take the whole system or hold parts of it and tested. That's in real life with all the dependencies, such as a data base. You'll see special techniques for isolating units filled A in this course in the section about Dez doubles. So as a result off the difference between unit and integration tests, it becomes apparent that unit tests should run faster and be more reliable. I don't want to look at the properties of unit that's closer right at the beginning, so it's enough for you to understand the difference I describe so far, you learn more about properties of good unit tests. Later, in this course, let's talk a little bit about unit testing frameworks 4. 03 Unit Testing Frameworks: before jumping right to writing unit tests. I want to say a couple of words about unit testing frameworks. Yes, In the real world, developers right unit bests relying on special unit testing frameworks. Perhaps the most popular frameworks are the following m s test and union and X unit dot net . I'm sure there's a bunch of other frameworks, but the intention of this lecture is not to compare different frameworks. The most important thought I want you to understand is that there is little difference between different unit testing frameworks. Yes, all of them have some advantages and disadvantages. What I'm talking about is that once you understand how to write unit tests with any unit testing frame, then you will be able to ride them with any other unit testing framework. It takes one or two days to grasp all the features off a particular unit testing framework . So if you have some experience with an unit and you've seen the vacancy, the requirement to be familiar with another unit testing framework don't draw attention to you. You easily can understand any testing framer along the way. So I chose the end unit s A unit testing framework to demonstrate examples in the course, and I can explain why, and unit is one off the oldest dotnet unit testing frameworks. And it has all the features required from a good unit testing framework. It is simple to use, and it integrates well with different tools, including visual studio itself. M s test is a framework integrated into visual studio by default, so to speak. M s test has the most powerful capabilities related to seamless integration with visual studio. But a mess test out of the box doesn't have some must have features off a good unit testing framework such as simple permit arised tests. And it also has some drawbacks regarding integration with continuous integration tools. But as I said earlier, don't be bothered by particular frameworks. They're just tools. Tools are important, of course, but union testing framers are very simple to learn. So it doesn't matter what unit testing framework we're going to use throughout the course. It will not have any serious impact. The last framework in the least, is the X unit dot net. I wouldn't recommend it at all. There is a lack of documentation about this framework and those pieces of documentation which exists are sometimes very unclear. So I would choose between N unit and M s test in the end. Okay, let's go to the next lecture and write the first unit test. 5. 04 Your First Unit Test: and here we are in the visual studio 2017. Something can be different in your visual studio, but don't worry, we're not going to do anything that you can do in older versions. Official student. So look at the solution. Explorer. We have irregular assembly here. Named Business. It contains some code implementing business logic. Now it has only one class, with only one ST Ick method in sight. Take a look. The method named Bar Sport takes a string parameter. At first, it checks if the argument isn't an appropriate form, but if it's not, it throws an exception. Otherwise it takes the sub string and forces the number of a serial port. This method represents a chunk off important business logic. We don't know whether it works correctly or not. What's right? A unit test for this method to check if the implementation is correct. Usually we create a separate unit test project for each project in the solution the code from which you want to test. For example. In this case, I'll create a separate project for testing the business project. Taken notice how I named the unit tests project. Usually we name them by starting with the name of a project which we want to test, and then we add a dot and the word tests to write a unit test. We need to install a unit testing framework so I'll go to you get package manager and installed and unit done before writing unit tests. We also need to do the following steps for writing unit tests written within unit from within the visual studio. We also need to install a special extension named and unit test adapter. Seems we're going to use the third major version often unit. Along the course, we need to install the and Unit three test adapter. Let's do this. I'll go to tools and extensions and updates. Here it is. After installing is complete, we need to restart the visual studio. I was do this to test the business project. We need to add a reference to it seems we're going to use types from it now. I can write a unit test in the unit test. I call the method we want to test passing to it. Come one string literal. I know that the correct result is one. So in the next line I use a special class from the in unit testing framework named Assert. The meaning off this class is pretty obvious from its name. We use it for asserting statements. In this particular case, we assert that the result has to be equal to one. So, in essence, asserts tell the test runner whether a test has passed or failed. I've written here to variance over the same assertion. The last one is commanded out and it is the old style off writing a search with in unit framework. We're going to use the guy off. The method named that for assertions. There is a special class ease with the equal to method is used. Don't worry, we'll talk about it later. In this course in unit tests, we always have electoral result and then expected result. The expected result denotes how we define the correct behavior of a system. Actual result denotes how a system behaves itself. In reality, our task is to compare the expected and actual behaviors. Okay, then we have a union test, but we also should have a way to run it somehow. How to run a unit test in visual studio, have a special window named Dust Explorer. Let's open it. You can open it by menu going to test Windows Test Explorer and it says that we need to build the solution. Otherwise, the visual studio will not be able to discover our unit tests. I would have build who? Still nothing. The thing is that we need to mark testing classes and methods by special attributes to make them discoverable. We need to mark glasses which contain tests with a special attributes. Best fixture. We need to mark testing methods by the test. Attribute. Let's do this. I'll rebuild a solution. And now let's open the Test Explorer. Hooray! Now we see our test. Let's click run old tests and our test passes. Let's check what will happen if we make the implementation incorrect. I'll change their last index of perfects to one, and let's around the test who it fails. You can click on the test and you'll see the details why the test failed. I'll turn back the implementation to the correct state, and I look around the test and it passes. Congratulations. You have written your first unit test. Let's have a brief discussion off naming conventions in the next lecture 6. 05 Naming Conventions: it's enough to write a single unit test to talk about the importance off naming conventions . There are no debates regarding name testing projects and testing classes. They're almost always named in the following style Name projects as follows Project under test dot tests, for example, Transaction model dot tests Name classes as follows. Class name under Test Best's, for example, calculator tests or customer tests. There are several ways of naming testing functions. I can mark out the three major different styles. First, the unit test methods name starts with shoud describing the overall ideal the testing method. For example, I should add two numbers. Second, the unit test methods name. Start with the name off the unit under test underscore, and the second part s in the first style starts with shoot. For example, some underscore shoot ed two numbers, and the third is my favorite one. It is the most complex, but I like it because it reveals the intention off the testing method in details. Here it is. The name of a function should consist off three parts separated by underscore symbols. You've seen an example off naming in this style when we've been writing the first unit test . I'll just show it again. Here is an example. Bar sport Underscore. Come one, underscore returns one. The name is separated into three parts. The first part is the name off the unit off work we're testing. It can be just a name off, a function under test or something more abstract like user Log in or remove user, user, log in and remove User are the examples off naming the first part by the so called use cases. Use cases are the super interesting topic, and I only can recommend a book to read because use cases are totally out of the scope of this course. The second part is the scenario of the testing process sometimes weaken just right here. The arguments passed in the function under test. Sometimes we can write more abstract scenarios like Invalid String Format or valid Logan. All in all, this part reflects the conditions under which the unit is going to be tested, and the 3rd 1 is the expected behavior. There are three ways off naming this part, depending on the outcome. Off the function under test. First, it is named returns Value, for example, returns a zero or returns false. Second, it is named Changes State were sent state, for example, set number 20 We name it this way when the outcome off function under test can be observed via its public properties. Because the internal state has been changed and actually want toe validate the correctness of the changes in the test method. Third, it is named calls dependency, for example, calls processing Gateway. We named the third part in this way. When we validate the correctness off interactions between objects, we will take a closer look at testing interactions between objects later in this course. Okay, now you know the rules off naming so that we can continue our journey to unit testing. Let's briefly look at how to run and debug unit tests in visual studio in the next lecture . 7. 06 Running and Debugging Unit Tests: in this lecture, I want you to get acquainted with the most often used features off visual studio regarding unit testing. Here, you can see that I've added another unit test, which checks if the function under test throws the format exception in the case off the invalid former off the serial port string. I do this with help off the generic throws method, but in this lecture we're going to discuss the topic off testing exceptions. I want to demonstrate some features off visual studio. You can see that I opened and being the Test Explorer window. Let's take a closer look at what this window offers. First of all, we have already used the Ronald Command. It triggers the process of building the whole solution in case the solution has not been built before clicking on this command and then rants all the Discover tests near this command. We have a run command with options. I'll click on that here. You can run on Lee the failed tests, for example, you can rerun the last training session and other options. You may not understand right now what is called coverage, but we'll look at it later in the course, the next feature is called Playlists. Right now we can see all the tests in the default play least named all tests. To create a custom playlist, you can select a bunch off unit tests and add them to a new playlist. I'll create a playlist for a unit test, which checks the exceptions. For that, I'll right click on the test go to add to playlist and new playlist. We need to give a name for a playlist. I limit exceptions checking and click Save Now. If I go to playlist, I see my newly created playlist. I'll click on it and in the list off unit tests. I see only those which are contained in that playlist. It is sort off a grouping technique. If you want to run only specific part off unit tests, you can create your own playlist or playlists and run them. If you make a double click on the test, visual studio will open the corresponding source file and set your car sir, to the test. Using the context menu. You can run tests separately. I'll right click on any test, and you can see here that I can run it or the bucket. If I want to debunk the test, I consider a break point and click on that menu item. Let's do this. As you can see, I reached the break point. Now I can debug the test, its usual cold step by step, with all the visual studio debugging features at hand, I'll stop the debugging. You can also group tests. There is a small icon on the top. Here it is here you can choose how to group unit tests by their name, space by the class and many other options. There is another small like, and you're the grouping one. Here it is. This option turns on or turns off the automatic running off unit tests. After builds, I'll turn it on and rebuild the solution, as you can see, after cleaning and rebuilding, all the tests ran immediately after the rebuilding process was completed. Great. Now you have some understanding off what you can do with visual studio regarding managing unit tests, you can make your life easier with all these features. Just try them in practice. Okay, let's discuss the benefits off writing unit tests in the next lecture 8. 07 Benefits of Unit Testing: First of all, let's answer the following question. What is the purpose of the unit test we wrote in the previous lecture before writing a unit test? We didn't know if that parsing method worked correctly with a unit test we contest. If that method works correctly, if someone unintentionally changes the implementation of the parson Method, a unit best will fail, showing us that something is wrong so we can discover the problem before shipping our software to customers. We now have the documentation, which describes the expected correct behavior from the system. As a result, the development team is more productive. Developers have more time to work on new features rather than fixing bugs. Allows to change and reflector existing code without fear to break something silently. Developers are just hey pure. Since night goals are over, complex systems covered by tests are easier to understand. Fewer defects in production, reduced business costs you get this are much faster than manual testing. Let's pretend that we have a window which uses internally parsing method. Without a union test, you need to run a program, go to that window and click some kind off a button, which triggers some logic inside of which that parsing method works. Only after that you'll possibly be able to validate the results with the unit tests. You can just press the shortcut to run all the unit tests and check if the coldest correct off course. But the reality is not so simple. Isett my seeing. But the overall idea is to have a safety net. That safety net is the set off unit tests, which we can automatically around and ensure the correctness off the system. A separate benefit, which can be marked out, is that unit tests are very helpful for continuous integration. Maybe we even can say that unit tests are the core part of the continuous integration process. What is the continuous integration process? In essence, from the unit testing perspective, look at the diagram. A developer introduces some changes into the system and rights unit tests. Then he checks in all the changes, including union tests into the source control system like TFS or get these chicken automatically triggers the process off running all integration tests and all the unit tests . If all the test pass, then code changes will finally be committed to source control otherwise and developer sees the errors, fixes them and checks the code in again. In the next lecture, let's talk about who should write unit tests and when. 9. 08 Who Should Write Unit Tests and When: many developers think that testers should write tests. Really, why the hell programs should be bothered by writing any tests. The answer is simple. If you don't write unit tests, don't treat yourself. It's a professional developer. Developers are responsible for the cold, the right. If you don't write unit tests than your an irresponsible programmer and you should be fired , sometimes we need testers. I agree with that, but testers are usually responsible for manual testing. Manual testing is, well, a test around your program clicks on the buttons and verified by eyes the correctness of the programs behavior. They will not write unit tests. That's your responsibility. It's a programmer to write unit tests and do it well. Imagine how long it would take to wait for results from a tester to be sure that that function you wrote the less time doesn't crash the whole system. It will take an enormous amount of time. Unit tests are much faster than Anya testers. Off course unit tests can't substitute the manual testing. Having unit tests doesn't imply that you don't need any manual testing to be performed, but the thing is that SL ready, said unit tests create a safety net for the developer Without unit tests, you can't change the code and to be sure that you didn't break something with the unit tests, you can easily introduce changes. When should you write unit tests off course, You don't have to write unit tests in hello world applications. You don't have to write unit tests when you write a draft, often application. But when you test some kind off idea or something like that, you should write unit tests for any kind of complex applications. To sum up, testers are usually responsible for writing or performing manual tests. Unit tests are much faster than manual tests, so they provide the feedback very quickly. Unit tests great a safe it in that enabling fearless. Introducing off changes. Don't write unit tests for pet projects, which are not much bigger than Hello World app. If you don't write unit tests, you're not a professional. In the next lecture, you learn about the responsibilities off a programmer 10. 09 Programmer's Oath: the problem off programmers. Responsibility is very important today. Programmers do not care any serious responsibility. For example, a bug in the code controlling the Iraq 25 radiation therapy machine was directly responsible for a two least five patient deaths in the 108th when it administered excessive quantities off X race. Another example. But the software error often am I m 100 for Patrick Surface to air missile system caused its system clock to drift by 1/3 off a second over a period off 100 hours, resulting in failure to locate and intercept an incoming missile. The Iraqi missile impacted in a military compound in the Haram, Saudi Arabia, killing 28 Americans. Programmers are not responsible for such failures. Doctors who make such mistakes will lose their license. Problem is, working process is not regulated official in any way that then of 2015 Robert Martin, a K Uncle Bob, wrote a block post where he came out with the programmers both to defend and preserve the honor of the profession of computer programmers. I promise that to the best of my ability and judgment, I will not produce harmful code, the code that I produce will always be my best work. I will not known only allow code that is defective either in behavior or structure to accumulate. I will produce with each release a quick, sure and repeatable proof that every element off the code works as it shoud. I will make frequent small releases so that I do not impede the progress off others. I will fearlessly and relentlessly improve my creations at every opportunity. I will never degrade them. I will do all that I can to keep the productivity off myself and others as high as possible . I will do nothing that decreases that productivity. I will continuously ensure that others can cover for me and that I can cover for them. I will produce estimates that are honest both in magnitude and precision. I will not make promises without certainty. I will never stop learning and improving my craft. At least three off these points are strongly related to unit testing and test driven design . The 2nd 3rd and fourth points are not possible to follow without practicing unit testing. Take your time to think about this oath. Seriously. Are you sure you want to be a programmer? 11. 10 Conclusion: in this section, you learned that a union test is a function which calls another function a unit and checks the correctness of the outcome from the cold function. The system under test is an object which contains a unit being tested by a unit test. A particular unit testing framework is not irrelevant from the perspective off writing Valuable unit tests. Union testing frameworks are very similar to each other. There is a couple off unit test naming templates. My favorite one consists off three parts. Unit under test. Underscore scenario underscore expected outcome. How to run and debug unit tests. Visual Studio detects tests After rebuilding the related projects, any programmer has to write unit tests. That is your responsibility. In the next section, you'll learn the basic features off the end unit testing framework. 12. 01 Outline: Hi. This is allies for full of a K engineer Spark from engineers park dot com, and we continue our tour on the unit testing. In this section, you'll learn. What guarantees does unit testing provide? What is the pragmatic unit testing? How Singleton's and stated classes harm the unit, testing the problems related to extracting interfaces just for the sake of dependency injection? How much discovery is enough? The problem off testing three Ville code. What really means the rule off a single concern? Testing in a single unit test In the next lecture, we will start from an interesting question. Do unit tests guarantee the success? 13. 02 Assert Intro: of the heart off any unit testing framework from the developers, perspective is its assertion. Motile modern and unit implements effluent, constrained based model off assertions. What does it mean in practice? On practice, we used almost for all the assertions, the that mattered. Here on the slide, you see the signature off a generic, that method. That except the actual result as the first parameter in the so called constrained object in the 2nd 1 The most important thing here concerns the second parameter. Let's dig into the model of constraints. Constrains are the heart off assertions. I want to demonstrate this system. From the practical point of view, I don't want you to cram into your mind all the internal types of the in unit, so I'll try to simplify things a little bit with no doubts at the top level, we have three major logical constraints. Here they are. He's has and does. These constraints are represented by the correspondingly named classes in the unit. The model off constraints is multilayered at the next level we may have, but we're not obliged. Other logical constrains Here they are phone, not some. This is not a full least but I give you the most often used. Let's look at several examples off using these constrains in this lecture, we will look at the examples on slides and in the next lecture I'll show you some examples in code, which you can download and play around with it on your machine. Take a look and the all constrained the O constrained can be invoked both on ease and has constraints. The first assertion here checks if all the items in the array contain the letter B. In this case, the constraint expression will be evaluated to true. Since all the string liberals contained the letter B, these constraint is comprised off two levels is and all the second assertion here checks. If all the items in the array are greater than zero, in this case, the constraint expression will be evaluated to true. Since all the values are greater than zero, these constraint is comprised of two levels has and all they not constrained can be invoked . Both on is and does constraints not is the constraint which allows you to build negative logical expressions. These examples are obvious, so I even don't see in your reasons to explain the meaning off these cold lines and details . The does constrained is most often used for writing assertions on strings. Here are three assert statements The 1st 1 checks If the string ends with the exclamation mark, the 2nd 1 checks if the string ends with a question mark in the last one checks. If the string contain a sub string goodbye, apparently the 1st 1 returns false, the 2nd 2 and the last one false. The has constrained is mostly used with the some constrained Khera. Two examples. The first assertion checks if there a contains any items starting with B a sub string. If there's a least one item satisfying this condition, the expression will return true in this case that the second item starts with B A, so the expression will be related to true and the test will pass. The second assertion checks if there are any items in the array of doubles, which are equal to 1.0 plus minus 5/100 the first item on differs from one Onley on 1/100 so the expression will be evaluated to true. Also, you can combine a logical testing expressions by using compound constraints. Here's an example. Here I use the or and end compound constraints by the way they not constraint is also considered a compound constrained. Okay, so the overall meaning of this lecture is that with the modern and unit, you can build assertions which resemble expression trees. In the next lecture, I ask him, through all the most common cases off assertions. 14. 03 Assert Demo: I added to the class character, which represents a character from a game. It can be an elf or a Norc with some amount of health armor, speed and so on. It doesn't matter how it is implemented. You can look on your room. Just don't lose the source files attached to this course. Let's have a look at the tests. These deaths are intended to check the behavior of the character class. The first group of tests shows how you can validate strings in your tests. Don't draw your attention to the name of testing methods. These tests are named like that just because thes tests were written for the sake of demonstration. Different features often unit not for the sake off writing real well written unit tests. So the first Union test creates a character with the name John, and after that, it asserts three things. The first is that the property name actually returns the value which was passed in the constructor. The second checks. If the name is not a name to string and the 3rd 1 checks, if that name contains a sub string O H n off course aerial unit test wouldn't contain these checks. These checks are here just for the demonstration, often unit features. In the real test, I would only leave the first assertion. Let's run this unit test to be sure that it passes. Okay, it passes. The second test demonstrates the feature off ignoring a string case. So we create a character with uppercase name John and then compared with the equivalent in lower case here, I use in the end the ignore case constrained. Let's run the unit test and it passes. I'll remove the ignore case constrained and demonstrate that the test will fail well around the test and it fails. I'll fix the test. We're on it. Great. Let's get to the next group of tests in you Miracle tests. The first test demonstrates that we can use the is equal to with numeric values. These test creates a character and checks. If the default health is equal to 100 let's run the test. It passes. Also, you can see here to commander outlines, which show how you easily can check the value if it is positive or negative. The next two tests demonstrate that you can use the same a p I with floating numbers in these two tests. We just check the correctness off a default speed for a corresponding type of character All around this tests and they pass. The last test from this group is a tricky one. This test looks very similar to the previous one, but it demonstrates the problem off. Comparing floating point numbers Lotus that I sum up two floating point numbers to get 1.4 value. Such calculations often recite in the production code, not in the test code, but it doesn't make the example bad. I'll run the test, and it fails. Why? The thing is that 1.4 and the result off summing up 1.1 and 0.3 are different values. There will be a tiny difference between them. If you want to learn more about why this happens, Google for it or look for a good see shop course. I'll just say that you should compare floating point numbers with tolerance. I'll commend out the first assertion and UN command the other two ways. Offsetting intolerance. The 1st 1 sets the tolerance to 0.5 and the 2nd 1 to 1%. So if the difference between values which are compared doesn't exceed these boundaries. Values will be treated as equal. Let's run the test, and it passes the same thing you can use with daytime values below. You can see the example. The following group of tests demonstrates the A P I for working with Bolin's and now's. The first test shows how you can check a value on now. A character doesn't have a name by default, so this test checks if the name returns. Now I'll run the test and it passes. The next test shows they buy for checking. Bullen values it checks if the character is dead after getting a huge damage. The last line demonstrates the older but still available in unit FBI. And actually, I prefer in such simple cases it more than more than a guy so you can use Assert, is true or assert is false. If you like it more, I'll run the test ended passes. I joined all the assertions in one test to show the features off checking collections. Here, you can see that I create a character and feel the collection off weapons by two weapons and life and the pistol. After that, you can see how to check if all the items in the collection are not empty. For using this constraint, the values have to implement the innumerable interface string implements innumerable so that you can apply this constraint. The Next line asserts that the collection contains an item knife. The next line asserts that the collection has exactly toe items. The next line assert that the collection has exactly one item the value off, which ends with T. O. L. The next line asserts that all the items are unique, and the next line asserts that all the items are ordered in alphabetical order. After this group off assertions, I create another object and at the same items to its collection. Off weapons and the final assertion checks either to collections are equal. Let's around the test to ensure that it passes and it passes. The next test demonstrates the A P I for comparing objects by reference. In this test, I just check if two objects are equal by their reference for that, I use the same s method. Let's run the test and it passes. But the following test demonstrates the guy off checking types here. You can see that I create the object that actual type off the subject is character in the assertion expression. I check if the actual type is character by using the generic version off the type off method. Let's run the test. Candid passes The following test demonstrates how you can check if a value false within a specified range. Here I check the value off armor by default. It should be greater than 30 and less than 100. In the commended outline, you can see another way of performing the same check. And by the way, the in arrange method includes the lower and upper bounder values. Let's run the test and it passes. The following test demonstrates the A pie off checking for exceptions. If a character gets the damage more than 1000 it throws the argument out of French exception. Here, you can see two ways of performing the same check I prefer the generic method throws passing to it, a Lambda expression. I'll run the test and it passes. That's it, as you can see and unit provide a very fluent syntax for writing assertions. In most cases, in unit provides a very intuitive A p I, which you may just guess how to use it for achieving what you want 15. 04 Arrange Act Assert: I want to stay at one important notion in union testing briefly. Remember that almost all the tests comprised of three steps arrange, act and assert. Take a look at this example. Maybe in the previous lecture you've seen simpler tests. But in the real world, tests are usually comprised of three steps. Arrange where you set up the system under test. Then you call one or a couple of methods. And at the last stage, you verify the correctness of the behavior by assertions. You may also hear that developers to refer to this concept s a A or three a. In the next lecture, you learn how to run unit tests from the console. 16. 05 Running Tests from the Console: Sometimes you need to run tests from a command line. For example, if you're setting up a custom process off continuous integration in such a case, you may want to create a batch file, the intention of which is to run unit tests from a deal. L. So let's look at how to run unit tests from the console to run the tests. We need to have a standalone installation off the in unit framework. I'll show you what I preinstalled before recording this lecture to download the standalone version. You can visit this site since I didn't need the runner with the graphical user interface, I just downloaded the end unit that consult the process off installation. It's fair retrieval, so there is no need to remove my installation for the sake of showing your installation process. I haven't stolen unit to program files slash and unit dot org's. So to run the tests, I'll first they open the visual studio command prompt. I already navigate to the folder, often unit, and to run the test from a deal, I can ride the following command. This command launches the in unit console program and passes to it a full path toe the assembly, which contains our unit tests. I'll press enter, issuing the command and all the desks bass, and we see the results here in the console window. The results are fronting. Unit tests are safe to the test result of XML file. By the way, that's how fairly simple you can run unit tests from a command line. 17. 06 SetUp and TearDown: There is a fundamental concept related to running unit tests. We need to have a mechanism which allows running some arbitrary code before each test and after each test. Let's look at the code and I'll show you why do we really need such a feature? We have four tests here. In each test, we have the same arrange process. In each test, we create a character object. Off course. There is an unnecessary duplication which leads toe on maintainable tests. We need to simplify things a little bit. I want to reflect around the arrange face. To do that, I'll introduce a private field. Done. Let's consider the last two tests. Actually, I wouldnt ride these to test a separate, but this example demonstrates the problem. Both tests check if the health property returns. Correct values after some damage was received by a character. Let's run these tests one after another at first eat passes and another one and it also passes They passed. Now let's run all the tests from this class. Oops, one test failed. Let's run the failed test separately. Who it passes? Let's try again to run all the tests. Oops, one test fails. Why does this happen? The problem here is that all the tests now share the same object we introduced s a class field. Initially, we had a good idea to make our code clear, but as a result, who have broken the code and unit allows to introduce a method which sets up the environment before each test. Let's introduce a set up method. Notice that I marked the set up method by special set up attributes. This attribute tells the in unit tests Runner to call this method right before calling each test method. Let's run all the tests again all the tests past. In addition, there is a tear down phase, which is supported by an unit as well. Imagine that the character class contains some kind off unmanaged resources. In order to avoid memory leaks, we need to dispose the allocated object before running the next unit test. Let's introduce a method which will be called after each call to a unit. Best. Let's run all these tests and all the deaths pass. I want to show you the sequence off executing unit tests. For that, I'll set to break points, and I'll did back of the unit tests set up, tear down, set up, tear down, set up, tear down, set up tear down. This is how union test Ragnar works. It calls a method marked by a set up attribute before calling each unit test, and it calls a method marked by the tear down attribute right after calling each test. 18. 07 OneTimeSetUp and OneTimeTearDown: We have a similar concept off running methods before any other methods on the level off name spaces and assemblies. Look at this code. We have two classes here. One is declared out off any name spaces and another within the business tests. Name space. The attribute Set up fixture marks both glasses. Each glass defines two methods. One is marked by the one time set up a tribute and another marked by the one time tear down attribute. The test runner will treat the class, which is marked by the set up fixture and placed out off any name spaces as the class, which sets up the environment for all the tests in the current assembly that that's Ragnar will treat the class, which is marked by the set up fixture attribute and placed within a name space as the class which sets up the environment for the whole name space. I'll said the break points at the following lines and I'll debug any test. Yes, you see, we reach these methods, taking into account that breathers lecture, look at the diagram which demonstrates the flow off executing tests by test runner here. It is at first methods which are adorned by the one time set up a tribute Iran for assembly or name space. After that glass after class, the same algorithm will be repeated and method decorated by the set up method Ron's. Then a test and then a tear down method and the same cycle again and again. In the end, methods adorned by the one time to your down attribute will run. 19. 08 Parameterized Unit Tests: para militarized tests is a very need feature supported by the end union. Emma's test supports Onley complicated data driven tests out of the box. Look at these two methods. They test the same just with different values. With perimeter rised test feature, we can reflector them into a single one clean test. Just look at how nice the test is implemented. Now, with the test case attribute, we can pass arguments into the testing method. In this case, this unit test will be called twice for the first test case, with 145 past as arguments and the second time with 80 and 65 as arguments. The first value will be passed as the damage and the second value will the past as they expected health. It is also possible to reuse the test cases by using the special test case source attribute . Here's how we can reflect her. Our example. - This feature allows you to write more complex the so called data driven union tests. Let's run this unit test and check if it works. All the deaths pass in the next lecture, you learn how to group and ignore unit tests 20. 09 Grouping and Ignoring Unit Tests: Sometimes you want to group several tests explicitly. For example, you have several tests which run very slow, and you want to separate them into a group. Logically, look at how you can do this. For example, I'll pretend that these two methods run slowly. I'll mark them by a special attribute category. If you want to see this category in the list of tests, open the test Explorer in group tests by trades. No, I need to rebuild the solution. Now you can seem the list the category off long running tests. The category attribute is applicable at the class level as well. If we mark the whole testing class, all the tests will be in that category. All the tests from this class are now in this category. Sometimes you want to ignore a particular test. For example, if a test is temporarily broken. If you want to skip a test market by the ignore attribute, here's how you can do this and the reason why you want to ignore this test. Well, that's revealed. You can see, and I can. Near the ignore test. The test runner didn't run this test. In the next lecture, you'll learn what is gold coverage and how to calculate this metric 21. 10 Code Coverage: I want to say a couple of words about the concept called code coverage. The coat coverage is a metric, which shows the amount of code, which is covered by tests it reflects. That amount in percentage, is calculated by dividing the total number off lines on a the number of flights which were reached. Enduring the process off writing unit tests to run the code Courage Analysis. Go to test, analyze code coverage and click on all tests. Waited a little bit, and visual studio opens a window. We shows their results here. You can see that in our solution. Roughly 80% off go discovered by unit tests. Expanding the tree. You'll give the statistics on classes and methods, for example, of the character class is covered at roughly 70%. If you want to highlight the covered and uncovered code, you can click on the button here. Gold coverage is an important metric, which reflects the health nous off the software. But let's take a little step back and we will return to this topic in the section dedicated to best practices in this section. Let's move to the conclusion 22. 11 Conclusion: in this section, you learned how to use the new assert that a P I off in unit you learned about constraints , which are used to write assertions how to write valuable unit tests with a triplet. In the first phase, you arrange the sad, then call the action or unit on the South. And in the end, you write the assertion CO. Theron tests from the console. These can be important to know in case of following continuous integration practices, how to remove duplication by using set up and tear down attributes. How to write permit arise to unit tests to removed application. Adhering to the dry principle, the so called don't repeat yourself principle, how to ignore and group tests Grouping can help you to track and organize unit tests to run them in specifically suited Bunches. How to calculate test coverage in visual studio test coverage is an important metric about high coverage doesn't guarantee that the software works correctly. In the next section, you'll learn what does doubles, including stops and marks are when you need them and how to both ride the manual and with a marking framework 23. 01 Outline: Hi. This is allies for full of a K engineer Spark from engineers park dot com, and we continue our tour on the unit testing. In this section, you'll learn. What guarantees does unit testing provide? What is the pragmatic unit testing? How Singleton's and stated classes harm the unit, testing the problems related to extracting interfaces just for the sake of dependency injection? How much discovery is enough? The problem off testing three Ville code. What really means the rule off a single concern? Testing in a single unit test In the next lecture, we will start from an interesting question. Do unit tests guarantee the success? 24. 02 Demo of a Testing Problem: in the previous examples when I showed you the features Often Unit I intentionally relied on the simplest cases. The code under test wasn't dependent on any external systems, resources or entities. But what if the code under test depends on, say, a processing center? If you need to test that such gold returns something specific in case off a specific response from the processing center, what would you do? You can just call a method which you want to test with specific input, Since the processing center will not return what you want here on the screen, you see a similar example. Let's say we want to test their calculate wage method, which implements a simple business logic. It calculates the final wage, depending on the result returned from the get working statistics method, which is a part of public AP I off the DB Gateway class. Look at this method more carefully. It depends unto obstructions. The 1st 1 which I have already said about, is the DB Gateway, and the 2nd 1 is the longer. Obviously the longer class is responsible for logging. Currently, it writes the information down to specific file on the disk. What the problems we will face if we decide to check if the business logic is implemented correctly. E g. If a customer is paid hourly than calculate, wage should multiply working hours on our salary. Otherwise, it should return month salary. I'm going to write a unit test in a straightforward way. - Uh huh. And how am I supposed to name this method? What I d Should I pass 10 Toe Way 1000. The production code will try to retrieve data from a database using that I d. And what should I expect? As a result, I don't want even to continue to suffer trying to come up with a bright i d. How to cheat the production code. It's impossible with the current implementation. This is not to tell that aerial connection to real database can experience a great number of fishes. What would happen if you managed to write a test? But the production code can't establish a connection to a database, right? Your test will fail. Thus your test will experience an uncertain behaviour. Eat may pass in one run and failing another. Yes. You understand this is a very bad thing. Okay, let's get back to the production code and analyze. Why is this happening? Why would face such problems trying to write unit tests 25. 03 Refactoring to Make Code Testable: the problem boils down to the design considerations of the customer type. The customer type has to dependence is and no one knows about them except the customer glass itself To fix the problems we need to grab ALS The dependence is under our control. How to do that with abstractions and dependency injection? Look at Harrell Reflector This example First of all, now the DB Gateway implements the I d be gateway interface and the longer implements the I longer interface. These interfaces just reflect the public ap I off corresponding classes. Since dependence is now inherit from interfaces, we can inject our own implementations which will do what we want them to do for the purpose We need a way to inject our implementations. There are two major ways off injecting dependencies via constructor and the property here are implemented. A constructor injection attesting code will be able to pass a dependency by a constructor. Another way is to roll out properties corresponding to dependencies like that. I'll quickly show you going this way. The client code can inject dependencies, survive properties. I always prefer the constructor injection over a property injection. Properties do not make the dependence is required to be passed. A client can just create a customer object, forget to set the dependency properties and start to use the object. As a result, a client will most likely face an exception or any kind of strange behavior, so always prefer a constructor injection. If you want to learn more about the best practices of designing and implementing AP, eyes in C shop, take my course, which is not surprisingly, called a P i n c. Shop. The best practices of design and implementation before writing tests. Let's have a brief theoretical discussion on different types of test doubles, and by the way, what is it has double. In the next lecture, you'll get the answer. 26. 04 Test Doubles: it's impossible to write unit tests for the code, which Inter operates with external dependencies directly during the process. Off unit test. Ronnie, all the tests you write for such code our integration tests, not unit tests to write unit tests for code with external dependencies, you have to replace those dependencies with placeholders that you can control. It allows you to remove the factor off uncertain behaviour off. Uncontrollable external dependence is to turn such dependencies into controllable form. We can use different so called test doubles which fake the behavior off that dependencies. And here we reach the point when we need to introduce menu testing terms and reach an agreement regarding their definitions. Please look at the diagram on the very top. You see, the term test double does double is a general term for referring toa. Any special testing objects which replaced the rial dependencies toe alter the behavior often original object in some way below. You can see one off the simplest forms off a test double called dummy dom is a test double , which returns values which are either now, in case of returning a reference type or close to zero in the case of structures at the same time. Dom. It's just do nothing inside methods which are not supposed to return anything below. You can see the stop. What he's a stop stub is a damn e, which is set so that it returns pretty. Find constant values from the methods called on the object, which that stop replaces. We use stops to drive the execution flow through specific pathways so that a unit tasked could test what it wants to dummy and stop are the test doubles, whose intention is to check if the return of values and state changes are correct? Other test doubles belonged to another type of testing interaction. Testing. The next type of protest double is the spy. This is an interaction test double, and it concerns the so called interaction fasting interaction. Testing is testing how an object sends messages or calls. Methods toe other objects. You use interaction testing when calling another object is the result off a specific unit off work? Let's give the definitions for remaining test doubles. Spy is a stub, which saves some information about the calls made on the spy it allows to verify in the test. What argument values were passed in the methods how many times any methods were called in what order the methods were called. And any other information you may need to use in the assertion phase of a test mark is the most complex does double from this brunch. Mark is a spy, but more contains assertions inside itself. So and Mark can fail the test. So and Mark saves some information. And if something is obviously wrong during the test asserts in that mark will cause the test to fail. It means that Mark knows what should happen in the case off one or another. Input values. At first glance, the difference between marks and stops may seem small or non existent. The distinction is subtle but important, because many of the mock object frameworks that you'll deal with in the next chapters used these terms to describe different behaviors in the framework. The basic difference is that stops can't fail tests. Marks can let me give the definitions off stops and Marx once more. The difference is very important. The distinction between marks and stops is important because a lot of today's tools and frameworks, as well as articles used these terms to describe different things. A stop is a substitute for a dependency in the system under test that allows the code to compile, and the dependency to return data is specified by the test. But importantly, Canada itself directly make a test fail. Don't get frustrated if you don't understand What does it mean? Right now? We will look at stops and marks ING practice very soon. In the other, Branch will have a notion off. A fake fake is the most complex test double. Yes, it's more complex than a mark. So what a fake is. In essence, fake is a test double, which simulates the behavior off a real dependency as close to reality as possible. You should avoid writing fakes. They're very hard to maintain in the long run. Each time a really dependence, he gets an update. You have to update the corresponding fake. Okay, let's write some unit tests with does doubles. In the next lecture 27. 05 Hand Rolled or Manual Test Doubles: I want the logging mechanism to be totally gloried in the unit tests. What? Type off a test double. Should we write for logging? Yes. We should write a damn e. We extracted the I longer interface, so we should just implement it. Let's do it Great. What llegar dummy does? It does literally nothing. Exactly what we want. There is another dependency which we also want to replace by the object which is completely under our control. I'm talking about the I d be gateway. In this case, we don't want to replace it by a dummy we want This does double to return specific values. So what type off it is double should be right in this case, right? Est ob We extracted the i d be gateway so we need to roll out our own implementer. Let's do it. In this case, the implementer returns a field which is suitable via the set working statistics method. Now we can write a unit test. Let's do it. Firstly, I'll set up of the stub. - I'll just best to the constructor off the set. The longer dummy implementation off the I longer we absolutely don't care what i d we pass to the calculate wage. Look at this test carefully. Firstly, I set up the main dependency db Gateway. Stop! I said they're working statistics, which I want to be returned from the get working statistics method. Then I create the sock and call the method. We want to test passing any I d. After that, I defined the expected wage, which is of course should be equal to 1000. Notice how beautiful this test is. I define a constant integer called any I D. This is a technique to write self documented tests by using descriptive names. Finally, I assert that the expected wage should be equal to actual within a small tolerance. Let's run this test. It passes. Now. We're sure that the logic off calculating the hourly wage is implemented correctly. If we want to check the correctness off inter operations between objects, then we need to write a unit test which relies on some kind off those doubles which track the calls. Such a test double is called Spy, for example. We want to check that calculate wage cause they get working statistics with the correct I D . In this case, we can write a spy like this. - The spy saves the information about the I D. Passed in the method in a property. Let's use this spy and write an interaction unit test. - In this test, we create a corresponding spy object and initialize the customer with test doubles. After that, we call the calculate wage passing specific values, and we expect that this concrete idea will be passed in the get working statistics method. We check this by using a spy property i d. Let's run the test. Oops, I forgot to set the working statistics. Great. It passes now. We're sure that the interaction between customer and DB Gateway is implemented correctly. Marks are very similar to spies. Let's roll out one now Let's write a unit test. - Let's run this unit test and it passes depending on our needs. We can remove the call to set working statistics, returning a default instance. But I'll just leave it as a tease right now That does double haven't used yet is the fake. I want to show you an example off implementation fakes reflect a real implementation off the dependency. For example, here I implemented and in the memory storage off working statistics, so our tests can work with this test suited storage. I'm not going to write a test since everything is pretty Others Just remember that in the real world, fakes off complex dependencies are very hard to support in the long run. Strive to avoid them when you can. Fakes usually require too much time investments. 28. 07 Problems with Manual Test Doubles: There are some problems with manual test doubles, by the way, we often refer to hand rolled test doubles as to manual test doubles, so there are some problems you may encounter while writing your own test doubles. The obvious problem is that you have to ride them on your own. What takes some time? You may encounter some difficulties writing test doubles for interfaces with lots of members writing a mark. You need to write a decent amount of boilerplate. Go to save information about calls. Imagine Complex marks, which save info about calls to tell methods and properties, and it's difficult to reuse manual written test doubles for other tests. So in then, once you get into more than three methods on the interface, everything starts getting tedious to maintain. You can use a so called marking framer toe. Overcome these problems. Let's talk about marking frameworks in the next lecture 29. 08 Mocking Frameworks: marking framework is used to create replacement objects like fakes, stops and monks there used to isolate dependencies and help developers in performing unit testing in a concise, quick and reliable way. Creating mark objects manually is difficult and time consuming, so to increase your productivity, you can go for automatic generation off mark objects by using a marking framer. Marking frameworks are independent off unit testing frameworks so you can combine them as you want. For example, you can use any unit and and substitute marking framework or Emma's Test and McHugh marking frameworks and so on. Marking frameworks can be divided into two camps. Constrained and unconstrained. It seems that these category names were introduced by a Roy Oshiro in his book. They are off unit testing. Under the notion Off Constrained Framework, Roy means a framework that is not capable of doing some extra things in other words, features. For example, constrained frameworks can't create does doubles for private methods and ST ick methods. Constrained frameworks generate code at runtime that inherits and overrides into faces or based glasses. With these frameworks, you can create as doubles only for the code for which you can create those doubles manually . If you can't write your own test double for a chunk of code, it means you can't create a test double for that gold with a constrained marking framework as well. Here's the list of the most popular constraint. Marking frameworks in the dot net world and substitute the youngest marking framework, which has a very simple yet powerful FBI. No que, that powerful marking framework, which is also very popular. Brian a Mark, very old marking framework, which has a difficult to use a p I. But Reina Mark is under review right now. Seemingly, it will be updated so track its way on your own. I can't keep this lecture on par with the current state off all the frameworks, and by the way, I don't need it. And I'll explain why shortly? What about unconstrained marking frameworks? Well, obviously, Roy Oshiro calls them unconstrained because they process almost unlimited power with the unconstrained marking framework, you can create a test double for literally anything for a private message for a static method. How the hell does it work? You might ask if you're a new calmer to the world off programming than I must warn you that it's hard to explain how such things that work under the hood anyway, I want to say a couple of words about how these frameworks work Under the CUD. Unconstrained frameworks generate code at runtime as well as constrained frameworks. The difference is that unconstrained frameworks are based on the so called profiling AP eyes. These AP eyes provide events for anything that happens during CLR code execution and even on advance that happened before the Net I'll code gets compiled in memory into buying a recode. Some of these events also allow you to change and inject new ill based goat to be compiled in memory, thus adding new functionality to existing code. A lot off tooling out there from the ants profiler to memory profilers already uses the profiling AP eyes. The most popular, unconstrained marking framework is the type mark Isolator. It was built somewhere around 2007. This framer has almost limitless capabilities, so the question arise why we may want to use constraint frameworks if we can use unconstrained. The answer is deeply related to best practices off unit testing, implementation. I don't want to dig very deep here, so I'll just briefly say why the idea to use unconstrained marking frameworks is not so bright as it might seem at the first sight. Good unit tests are just regular clients of the production code. I'm sure you know that irregular client can't call private methods. It can call on Lee public members. Tests which need to create those doubles for private methods are very suspicious, Most likely if you need to cheat the public FBI. Somehow you have problems with the design. You need to reflect her the production code to enable simple unit testing. Otherwise, if you start to write unit tests that need to harness limitless power of such tools like Type mark isolator, you come out with very hard to understand and how to maintain unit tests in the long run with us. Such powerful tools, which allow cheating public AP eyes developers inclined to use in case off working on the Legacy code base legacy code basis are often built badly with heart toe test AP Eyes such gold basis often are not covered by tests, and when the day X comes, developers need to understand which way they want to go either to write software from the ground or to maintain and extend the existing code. Base writing is often impossible due to public office reasons. So when developers understand that they need to maintain and change the existing poorly designed legacy code base, they also understand that they can't change anything because of the fear off. Breaking something toe overcome this fear. They need to cover the existing code base by unit tests. And at this point there are two ways either to apply advanced techniques off re factoring or to use such powerful tools like type moke isolator. This is the scenario which describes when developers might want to bring in tow, play unconstrained marking frameworks. So the corollary is that you don't need and shouldn't want to rely on unconstrained marking frameworks unless you're absolutely sure that this is the only way you can go otherwise choose the way off re factoring and cleaning the code base. The last point concerns the problem off choosing a particular marking framework. I said earlier that it doesn't matter what unit testing framer to choose from the learning perspectives. The same is true regarding the marking frameworks. They're very similar. It doesn't matter which want to peek. Having experience with one of them, you can learn any other marking framework with ease. I chose the and substitute just because this is the most popular framework nowadays. Okay, In the next lecture, I want to show you an example off using the and substitute marking framework, we will use it for your writing. All of the test doubles were wrote previously. 30. 09 Writing Unit Tests with a Mocking Framework: for replacing the dependence is I'll use the end substitute marking framework. I'll go to Newgate, package manager and installed and substitute. Let's right the first union test. They stand checks that the system under test returns correct. Wage. I want to create a test double for the I. D. Be Gateway using and substitute. I need to use the substitute class with the method. For now , I need to set up. This does double. I want to return for any I. D. The instance off working statistic I created here for this. I will use the following a p I often substitute. This expression sets up the test double to return for any I. D. The working statistics instance. Now let's define the expected wage and create a system under test. The Luger is replaced by default as double. We don't want it to do anything. It will not react to any calls. It will just ignore them. This is exactly what we want from the longer. Now I want to call the action and then assert Let's run the unit test and it passes. Let's rewrite the second union test. These test checks the correctness off interaction between the system under test and its dependency i d. Be Gateway lets you write it for that. I'll create that as double for the I. D Be gateway the same way we did in the previous test, and I'll set it up for returning a default working statistics on any call off the get working statistics method. Now I'll create ASAT and call the action. The last thing I want to write is the assertion in this particular case, I'm not going to use the Assert class in this case. I need to call a special FBI member, often substitute to check if they get working. Statistics was called with a proper i D. Let's run the unit test and it passes just for the sake off, ensuring that the test actually tests what we want. I'll change the i D and I order around the unit test and the test fails. I'll get back to the correct i d great. There's no meaning to rewrite the third unit test. The third unit there's demonstrates the same chick as the checking the second test. The difference is that the second relied on a spy and the third relied on a mark. The thing is that there are no spies in marking frameworks. Marking frameworks always work with full fledged marks, which track all the calls by default. So there is no meaning to rewrite. The third unit that seems the 2nd 1 and the 3rd 1 will be the same in this lecture. I just wanted to show you how you can use a marking framework to avoid manual test doubles . In the next lecture, you'll get a more detailed introduction into the end substitute framework. 31. 10 NSubstitute Mocking Framework: let's start from the beginning. The first others feature off any marking framework is the feature, which allows to set returning values from the marked out methods. In the previous lecture, you've seen an example, but let's repeat it once again. Look at the test we wrote here in this test are explicitly declared the constant named any I. D. This is a very good descriptive name. In this particular test, we can harness the feature off matching values to remove this line off code without making the test less readable. And substitute provides the class named Argh! I'll type it in. Look at the end, Ellison's Now I want to say about two methods. Generic any and these methods. In this particular case, it doesn't matter what very were passing into the method so that we can use the any method . I'll also replace the other case of passing the value. You might think that you can mark on the methods, but you can mark almost anything you like the same way as methods. You can mock the properties. I'll end the collected property to the I D Be Gateway interface in the calculate wage. I want to check the connection before calling the get working statistics method. If there is no connection, I want to return zero. Now if we want the test to pass, we need to mark the connected property. Let's do it. I don't know. Let's run the union test ended passes. I'll command out that check for keeping other tests green. That was just for the sake of demonstration, by the way, one simple but important fact. If you mark the same method more than once the most recent of a ride the previous. For example, if I will do the following in the end, the get working statistics will return these instance off working statistics, not the previous one. The previous call will have no effect. Another cool feature is related to exceptions. What will happen if Gateway throws an exception? We should be able to test such scenarios. I'll add the exception checking into the system under fast Let's check if the calculate wage return. Zero. In case of any exceptions thrown from the gateway, I'll write the unit test, - and here we can use the throws a P I often substitute to force the test double to throw an exception. Here's the remaining part of the unit test. - Let's run it grade. It passes before moving to the next teachers. I want to show you another real example. Here is the device class. It doesn't measure what the device we're talking about from learning perspectives. This device takes an instance often object, which implements the I Protocol interface. It saves the protocol, object in the field and then initialize is a test completion source. For those who are not familiar, this is a special class which can be used for manual setting. The result of a task task is the class, which was introduced in dotnet for te scraps, The thread and these very need for writing multi threaded code device class exposes two methods. Find and connect. The Connect method just tries to use the protocol to connect to a device thrice. If three attempts were failed, it returns false. Let's say I want to write a test, which checks give. The connect method calls the Connect method one of the I protocal thrice in the case off unsuccessful attempts. Let's write a unit test. It doesn't matter what argument to pass in the connect method in this case. Previously I defined a constant named something like any I D or it could be any port in this case, but and Substitute provides the future off matching arguments which allows in such cases to avoid declaring excessive variables. I'll use this feature as I showed you before, - and now I want to verify that the I Protocols Method Connect was called thrice. For that I can use the same method received. But in this case I'll pass the parameter, which tells and substitute to check the number off calling attempts. Here's how we can do this and now I want to verify that the I Protocols Method connect was called thrice. For that I can use the same method received, but in this case, L past the perimeter, which tells and substitute to check the number off calling attempts. By the way, if you want to check if a particular method was not called, you can use the counterpart of the received method, which is called not received. This method is similar, so there is no meaning to give a separate example and let's run the test and check if it passes and it passes great with the receive method You also can verify calls to properties before moving to the next feature. I want to add a couple of words about the fisher off matching values. If you want to return a value from marked out method on in case off a specific input, you can use the R E's method in this case. For example, we might want to return true in case off a specific serial port. Here's how you can set up their mock to return a specific value in case off a specific input. You also can use the expressions like this. This is very neat and powerful feature. I'll get back to the previous implementation. Let's look at the find method in the device glass securities. The find methods subscribes for the searching finished event of the I protocal interface. After that, it kicks off a command to search for a device they searching may take a long time. So the method start a new task, calling the search for device method. Then it returns the test completion source in the Event handler. It sets the result off a task. In this particular case, we could avoid such complications, but believe me that in the real world. Such scenarios are usual. How can we tells this method? We need to raise the event somehow, and substitute allows you to do this easily. Let's write a unit test. At first. I'll create a mark for the I Protocol. Then I'll create a device, and I'll just go to find method. Find returns a task. Now I'll define a constant port name. And now here's the in substitutes feature for raising events. - What happens here? The Rays event is the genetic method. Generic parameters should reflect the signature of the event. In our case, this is event handler off device searching event arcs, invoking the event you need to pass the parameters. So I pass, seen the provider and create the new event. Arcs instance. After that, I can assert that the test result is equal to what we expect. Let's run the test great, it passes. That's pretty much for starting with and substitute to write great unit tests powered by Marx. In the next lecture, you will learn what different approaches to unit testing exist 32. 11 Detroit School vs London School of Unit Testing: ignoring the historical aspect. I can say that there are two main approaches to testing. One is called classic or Detroit school, and another one is called Monarchist or London School. I want to say a couple of words about the difference between these approaches from the test doubles perspective. This is a basic unit testing course, so I don't want to dig very deep such advances topics. Thus, here is the basic difference between the two approaches Floyd May described in his block. The difference s this. The Detroit school off TDD tends towards using assertions to verify the state after the act phase. But that is by observing the return values or things that reveal the state of the system under test. We verify that the behaviour of the system is correct. The London style of TDD, sometimes called monarchists, tends towards verifying the interaction between objects. Did the system under test interact with its collaborators in the right way? Does it call the right methods in the right order with the right parameters, the right number of times? You'll notice that in both samples I'm cheating a bit and hiding the arrange face from you because the differences which might be significant are not what I want to call your attention to. Last days. Developers start to realize that the most powerful approach to testing should be pragmatic without inclining to any schools, The best way is to use techniques and tools in most appropriate cases, maximizing the benefits and reducing potential harm. We will discuss the pragmatic approach more closely in the section dedicated to best practices off writing unit tests. Now in this section, let's move to the conclusion. 33. 12 Conclusion: in this section, you learn that you need to rely on test doubles when you have to replace riel dependencies on those which are under your control. How to effect her the production code. To make it testable, you need to make all the dependencies visible to the client code. How to write different as doubles, such as fakes, damage stop spies and marks diamonds, do nothing stubs, return specific values. Spies, travel information about the calls and mocks our spies, which can verify the correctness by themselves. How to use a marking framework to avoid problems related to writing. Manual test doubles The difference between classic Detroit School and monarchists London School The classic school tries to avoid marks as much as possible, while marks and interfaces are the core part of the system emerging process for London school followers. In the next section, you'll learn what it's d d d and look at a practical example 34. 01 Outline: Hi. This is allies for full of a K engineer Spark from engineers park dot com, and we continue our tour on the unit testing. In this section, you'll learn. What guarantees does unit testing provide? What is the pragmatic unit testing? How Singleton's and stated classes harm the unit, testing the problems related to extracting interfaces just for the sake of dependency injection? How much discovery is enough? The problem off testing three Ville code. What really means the rule off a single concern? Testing in a single unit test In the next lecture, we will start from an interesting question. Do unit tests guarantee the success? 35. 02 What is TDD: There's driven development, which is also called Test First Development is the approach off. Writing tests head over the production code, so tests drive the production code, not vice versa. As usual, the goal is to keep the design well structured and modular to enable writing off valuable unit tests. That's why sometimes developers refer to t d D not as to test driven development, but as to has driven design. Because tests for the shape off the production code before TDD was introduced, developers just rode the functional code. And when all the pieces were put and interconnections between them are set up, developers started to think about writing unit tests going this way. Very often, developers face the problems with writing unit tests, since the design of the functional code is not suited for unit testing, no proper abstractions, no Sheen's for injecting the dependencies and so on. Unit tests are specifications off what the code should do. When developers right unit tests in the first place, they implement Onley that production code, which satisfies the unit tests. Otherwise, developers tend to ride generalized and thus more complex code. Developers also tend toe gold plating de de de helped tow. Avoid all these problems when you write unit test first, you can't avoid thinking about how to make the production code design testable, since in the first place you need to make the already written unit tests. Bass following two D D practices, developers achieve more even gauge of progress between testing and coding. Obviously, it automatically provides at least about 70% off test coverage. Here are some a very popular misconceptions related to TDD writing tests. First, you double your efforts. Well, I even don't know where this misconception came from. You'll write unit tests anyway, so why not to write them at first? And we're in the case that the doubling off efforts, the fact is that TDD reduces production box density by 40 to 80% without tests and even adding tests after you implement production code, many more bugs get into production, and everybody that gets into production doesn't simply waste developer time. It hurts the company's brand and quality reputation. It wastes enormous resources in customer suffered costs. Maybe you just don't want to write unit tests at all, then you're not one of us. Sorry. That's all I can say if you want to write software of poor quality, Go on. And don't forget to request a refund to get your money spent on this course back. I don't want to see such students enrolled in my course. You can't write tests until you know the design and you can't know the design until you implemented the code. Developers who have not developed the test first TDD discipline, often charging to the implementation off the code before they know what they pay. I will look like they start implementing code before they have even designed the function signature. This is the opposite off TDD that the point of TDD is that it forces you to have a direction in mind before you start charging into the fray, and having a direction in mind leads to better designs. You have to write old tests before you start the code 100% design up front is a myth. In every type of engineering. The design is exploration, Cherie. We try things out, throw them away, try different things until we reach something that we like now. True, if you wrote every test up from before you wrote a line off implementation code that would hinder the exploration process. But that's not how successful TDD works instead, right? One test. Watch it fail, implement the code, watch the test pass and repeat. In the next lecture, you learn what a red green re factoring means. 36. 03 Red Green Refactor: The main technique off TDD is called Red Greener. Factoring Red Green. Red Factor are short names off three repeatable steps. Imagine that we need to implement a calculator, which adds to numbers. The first step we need to make is to write a union test so we can write the following unit test. Now. If you build a solution, you'll get compilation errors. Since we haven't implemented this AP I yet, let's generate all the code. I'm generating the code with help off such a powerful tool as very sharper productivity. Tools like Re Sharper significantly enhanced the TDD experience with extremely powerful features of generating code navigation, smart quick fixes and other. Okay, let's run a unit test and it fails. Now we are in the red phase. At the second step, we need to ride the production code and turn the unit test green. Now let's run the unit test and it passes great at the third face, we need to look both in the production cold and testing code carefully. If anything requires re factoring, we need to perform a factoring. Since we're having, for example, we don't need anything yet. The only thing I can do here is to just move the generated code to the appropriate place. So this is the whole reflecting we did here. So we get back to the first step, we need to write the next unit test, but I'm not going to do this. So you should repeat these simple three steps until a feature or a use case is implemented . These simple three steps technique is the core technique off TDD. 37. 04 TDD and Design Upfront: programmers who are just at the beginning of their TDD way very often got confused regarding the problem off upfront design. The thing is that separate articles which describe T d d show the basics, including the overall idea and the red green red factoring technique. And that's all. This is a quint essence off all the articles out there. These articles completely forgot the problem off big design or architecture. In other words, reading those articles, developers get the feeling that test drive the architecture. You just write deaths, and the system emerges by itself automatically, so to speak. What I want to say about this is to forget about this bullshit. Please don't believe in such horrible, silly articles that state that tests drive the big architecture. This is just craziness. All the method illogical practices like gathering off requirements, writing off use cases are not gone. They're all still there. We need them. We can't write gold without keeping in mind a big picture off what we're striving to achieve. Yes, TDD helps to drive the design. Did you hear that? It helps. De de de doesn't replace the whole pile of different practices off analyzing the self to a project de de de helps to come up with good AP I names concise implementation but you can sit on right goad without bearing in mind what you're going to achieve. What would you write in such a case? So don't believe in fairytales. TDD is the implementation technique in the first place. It helps to emerge good design. But as I already said, it only helps what doesn't mean that TDD fully defines how the upcoming design will look like. So before writing anything, sit down and at least draw a sketch off what you want to achieve. What use cases do we want to implement? Who are the actors and so on and so on? I can dedicate to the stopping hundreds of courses. Obviously, we're not going to discuss this face off software development. Thank you. 38. 06 Conclusion: in this section. You learned that did it? He is the approach off writing tests ahead of the production code. TDD provides at least 70% test coverage. De de de doesn't cancel all of analyzing techniques you still need to write use cases or user stories and other related stuff. How to apply to D. D with the red green manufacturing process. In the next section, you'll learn the best practices off unit testing. 39. 01 Outline: Hi. This is allies for full of a K engineer Spark from engineers park dot com, and we continue our tour on the unit testing. In this section, you'll learn. What guarantees does unit testing provide? What is the pragmatic unit testing? How Singleton's and stated classes harm the unit, testing the problems related to extracting interfaces just for the sake of dependency injection? How much discovery is enough? The problem off testing three Ville code. What really means the rule off a single concern? Testing in a single unit test In the next lecture, we will start from an interesting question. Do unit tests guarantee the success? 40. 02 Do Unit Tests Guarantee the Success: does a project with code base covered by tests have more chances to succeed than a project with the code base, which is not covered at all? Well, it's a silly question, frankly speaking, a great number of projects written with unit tests in mind successfully failed unit tests by themselves do not guarantee that the project will not suffer from classic diseases like poor maintain ability. Sometimes things get even worse. Unit tests can cause more problems rather than solve them. Badly designed and poorly written unit tests become an additional baggage, which you should maintain. Unit tests are liability. Remember that unit tests require as many attention as the production code base does. If you violate all the design principles, expect very bad consequences. Writing unit tests is the craft, which you should start it carefully. Nevertheless, unit vests are very important to have. Try to answer a strange, hypothetical question. Imagine that you have a big project with lots of gold. All the goat discovered on 100% by perfect unit tests pretend that something bad happens. And what would you prefer to lose? All the code base aural. The unit tests off course. It's hard to answer this question, but this is a good mind banding exercise developers who understand the true value off. Would unit tests refer to lose the code base rather than lose the unit test suit? The thing is that you can recover the code base from unit tests, but not vice versa. Unit tests can be recovered from the code base. In short terms, it might be more beneficial to keep the code base and lose the unit tests. But in the long run, it seems that it would be better to save unit tests and lose the code base unit. Tests do not guarantee anything, but good unit tests are worth off investing time and money. 41. 03 Pragmatic Unit Testing: Here's a brief description. Off main points off Pragmatic unit testing. The main idea is to write highly valuable tests. So the question is, what makes available Test available Unit test has a high chance of catching a regression error. A regression error usually means area. Peering bug. Imagine that a bug was discovered in the production. You fix the problem and wrote a unit test covering the case, which led to a bug. A good unit test, once written, should protect us from reappearing off the bug. A valuable unit test has a low chance of producing a false positive. False positive means that a test says that everything is fine, while in reality everything is bad available. Unit test provides fast feedback, and a variable unit test has low maintenance cost. On this diagram, you can see the correlation between three types of tests and value proposition. As you can see, unit tests provide the fastest feedback. You click a button and in a matter of seconds, get the feedback. Integration tests are much lower. They involve rial dependencies such as data basis and online services. Also, unit tests can be Iran in peril, while integration tests cannot and toe end test is a sort off integration tests. They're just bigger than integration tests. Integration tests are intended to test a part of a system usually sometimes even marking are laundered parts, while end to an tests include all the possible mechanisms and the system as a whole. Integration and into an tests provide better protection against regressions and false positives. They just thinks how they go in real life. This is the primary reason, at the same time, well written unit. This have a lower maintenance cost, since they are at least simpler to implement. Another important point is that unit tests should not test the correctness off interaction between domain objects or, in other words, between objects, which implement all the business logic related to a problem domain. Such tests experienced lots of false positives and worst maintain ability, since they usually involve the writing off marks. Unit tests written with marks are always less maintainable than unit that's written without them. Regardless of how marks are implemented either manually or with a market framework, such tests produced lots of false positives. Since the FBI, off collaboration between the main objects changes frequently, we should write interaction tests verifying the collaboration with external systems. Since the public FBI in this case changes rarely always choose to use interaction. Testing only is the last option. This is very important. Try to rely on tests that verify state or returning values because so many things become much more complicated by having interaction tests. But sometimes it's in the case of 1/3 body call to a longer interactions between objects are the end result. That's when you need to testing direction itself. The considerations of pragmatic unit testing are different from what classic or London school suggest. For example, in one of the most famous books that advocate the London school approach, named growing object oriented software guided by tests by Steve Freeman and Net Price, they suggest to use Marx and stops for design purposes as a way to emerge the design off the software. So authors are okay with the idea to extract into faces just for the sake of creating shames for injecting dependencies and writing marks Afterward. We will also briefly touch this problem in the lecture dedicated to the problem off interfaces, which have a single implementer. If you ask me, I'll say that I don't like the approach advocated in the book off Freeman and Price. I'm more inclined to rely on the principles off pragmatic unit testing. 42. 04 Integration Tests: sometimes here and there. I hear that integration tests are pure evil. There's annulled article, which is attached to this lecture. For instance, in that article, the offer claims that integration tests don't bring any value to the table. One of the main points is that big software contains a great number of tears and branches. And when we multiply some numbers who end up with hundreds off thousands off possible execution paths and thats the conclusion when you're thousands off integration tests, which are, of course, fragile. In addition, what a deep observation got sake? Actually, that was a sarcasm. I immediately start to feel tired when I'm going to explain why such observational are meaningless because it's boring. However, at the same time, I understand that this is my duty, a serial world developer. So let Mortal Kombat begin. I wanted to make this lecture fund, so I prepared several finding gifts. I'll try to illustrate the problem by showing you those finding gifts. Let's get started. These GIF illustrates what could happen if you have a unit test, which verifies the correctness of the door latch. It doesn't mean that it locks the door correctly. The developer didn't write an integration test, which verifies the correctness of the systems behavior on the slide, you can see that a developer wrote to great unit tests. The 1st 1 tests the left window in the 2nd 1 tests there, right window. Unfortunately, that developer didn't write an integration test, which verifies the correctness of the system. If you wrote such an integration test, he would face an exception and fix the problem. This is another great illustration off integration tests absence. I would even say that most likely in this particular case, a developer had to write a full fledged and to and integration test. Sometimes it's not enough to write a couple of integration tests, which verify the correctness of different parts of the system. We need some enter and tests which go through the whole system, verifying interaction between big components off the system. This slide illustrates how developers see the system through the prism off unit testing. They believe that everything is fine. But as you might notice, this is far from being something we might want to achieve. They slide illustrates how we often see our program is working during a debugging session. Very strange things happen. Often we face such situations because off integration test substance good integration tests reveal the internal problems via verifying the external behavior. And this slide is a good illustration of how any big object oriented programs work. A great number of objects leave very closely to each other. They sent messages, received them KAL eight with each other and so on. Looking at this slide, answer me. Do you really think that you can avoid writing integration tests? This course is dedicated to union tests, but I must say that we absolutely need to write integration tests, at least in huge systems. The number off union tests should be at least 10 times greater than the number off integration tests. But it doesn't mean we shouldn't write integration tests or treat them as second class tests. No, they're first class citizens, so pay close attention to how your system works as a whole. In the next lecture, we'll talk about Singleton's and stated classes and why they're obstacles on the way of your testing. 43. 05 Singletons and Static Classes: For those who are unaware of what Singleton is, Singleton is a creation all design pattern, which allows defining an object which can be created only once. So in the program, there can be only one instance off such an object. That's why the design pattern, which enforces this restriction, is called Singleton. State of Glasses are somewhat similar to Singleton's, but they're far from being the same. Though they induce similar hard to unit testing, you'll see this shortly. This code uses the M S test framework. We've seen how to use any unit for defining method, which will be executed before any other unit tests in the assembly in there must test. You can do it with the assembly initialize attribute. It actually doesn't matter. What matters is that such initialization is most often are the sign of problems. This method calls some method with an interesting name, innit config and you. I context. With this method, initialize is some kind of configuration and marks a your thread with a slick trick. Our interest lies in the configuration class. The first line initialize is a configuration class which is used everywhere in the code base via stated property in the state of app glass. Because of that, you can just easily right any unit tests for the code base, which relies on that configuration. You also can't market easily, since the code base uses that configuration directly via stated property. Thus stated, core global dependencies are harmful to unit testing. Such stated dependencies lead to a very complicated stage off, setting up all the static or global dependencies to a correct state. Before executing unit tests, I intentionally showed you a real difficult case from a real code base. You can consider the same problem with the Tor example. Here it is. Here's the simplified version with dependencies implemented as Singleton's. There are several implementations off the singleton design pattern, and each of them has some peculiarities. I don't want to dig this topic deeper, since it's irrelevant or discussion, I'll just use one of the possible implementations. Consider a synthetic but very close to reality example. Here's credit card class with a charge method, the intention of which is obvious from its name. This method depends on global state heavily. Firstly, it tries to validate a card, then gets a customer, validates a customer and calls the charge method. In the end, all the operations are called on Singleton's Let's look at one of the Singleton's no sense to look at them all since they're implemented. Similarly, for example, look at the credit card processor. The singleton itself is not stated, but you can create it. Since the constructor is private. The only way you can use this Singleton is via the state IQ instance property, which grades the object if it was not created. The problem is that this glass requires some initialization. It exposes the set connection method in reality, who most likely had to pass some arguments to eat. If you try to call, validate or charge before setting up the connection, you'll get the exception in this particular toy example. We could solve the problem by automatically wire up the object right after the creation. But again, this is a tour example. In the real world, most likely we would have to expose a separate initialization method like this set connection in the real world application. All these Singleton's most likely would be initialized somewhere in the main method, like here and now I want to ask you, How the hell are you going to test the charge method. At first, you need to pollute your tests by some horrible preliminary initialization. Without it, tests will not work. Secondly, how the hell are you going to manage the dependencies? You can try to write some test doubles and you'll soon realize that this is hardest hell if possible at all, without involving some kind of dark magic. What is the reason off such a horrible situation? Off course. The primary reason is a poor design. This design is untested herbal, the charge method and the created card glass. They hide the fact that they depend on three entities. This design should be completely rewritten. All the dependencies should be visible from the outside world. Previously, I showed you the technique which enables a constructor injection. So I'm not going to repeat the same exercise you can do. It is your homework. So why Singleton's are bad? They're generally used as a global instance. Why is that so bad? Because you hide the dependencies of your application in your code instead of exposing them through the interfaces. Making something global to avoid passing it around is a code smell. They violate the single responsibility principle by virtue of the fact that they control their own creation and life cycle, they inherently cause code to be tightly coupled. This makes faking them out under test rather difficult. In many cases, they carry state around for the lifetime of the application. Another heat to testing. Since you can end up with a situation where tests need to be ordered, which is a big no no for unit tests. Why? Because each unit tests should be independent from the other. 44. 06 Header Interfaces: As I said earlier in the book growing object oriented software guided by tests, authors suggest extracting interfaces to enable loose coupling emerging the whole system this way. I also said that this approach is called the Approach Off Markets, or the London School and main developers don't like this approach. One of the primary science off the markets approach is having interfaces with a single implementation. I want to share with you some very important thoughts regarding this problem. I am inclined to treat the case when you have only one implementation off. A given interface s a code smell. I'll try to explain why Esmark Seaman said in his block programming to an interface doesn't guarantee that we're coding against an abstraction into faces are not abstractions. Why not? It will see why in a minute here, I want to say that such interesting questions I discuss in detail in the course a p i n C. Shop. The best practices of design and implementation interfaces are not abstractions. And here's why, when you use the extract into face reflected all feature in visual studio, even if you don't extract every member, the resulting interface is shallow because it doesn't recursive Lee extract into faces from the concrete types exposed by the extracted members. An example I've seen more than once involves extracting and interface from a link you to sequel or drink. You turn to this context in order to define a repository interface. It's an example. Here's into face extracted from a very simple in Q two entities Context At first glance, this may look useful, but it's not. Even though it's an interface, it's still tightly coupled to specific object context. Not only does objects set off t a reference the entity framework, but the posting class is defined by a very specific photo generated entity context. The interface may give you the impression off working against loosely coupled gold, but you can't easily if it all implement a different I posting context with a radically different data X technology. You will be stuck with this particular posting context. Another way we can create problems for ourselves is well are interfaces leak implementation details. A good example can be found in the System rapper project that provides extracted into faces for various busy all types such a system dot io dot file info Why developers meet such libraries as the System rapper. Here's the use case. A developer, right? Some kind of application, which needs to read the file, parse it, using some kind of specific format updated in that format and remove them. In this particular case, we have a class named quotation processor it except a file path in the constructor, and it exposes two methods. The first method. Get amount, converts one currency into another. The logic doesn't matter. This method reads the file. It parses it and returns the results of calculation. Otherwise it returns minus one. The second method at Quotation also reads the file. If there are any records, we take the last one parse it and then we're four months a new record and finally added, If there are no records, we form a new record with I D equal to one. This is a little bit silicon example, but imagine that everything is much more complex in the real world. Examples. So how a developer who rolled this class solved the problem. The developer rolled out a class which is responsible for everything. It can read a file. It parses it and process it afterwards that developer starts to think. How the hell am I going to test it? And if you look more carefully, you'll immediately understand that there is no way to write unit tests for this implementation. All the functions depend on the file class, and they directly operate on the disk. That's how System Rapper comes into play ride. I'll add the System rapper library to my project, and my class will require that I file interface in the constructor so I could market and write unit tests. The thing is that the logic of that programmer is flawed. Always try to find the roots of the problem. The reason why the developer experienced difficulties with the unit testing is not related to the fact that the application needed toe work with the file system. No, the reason is that the single responsibility principle was violated and principles of functional design over totally ignored. That programmer, instead of bringing useless marking libraries, could separate the responsibility off reading and writing to a file from the business logic off formatting and passing. After that, he could easily right unit tests for business logic and right integration tests for the class, which Inter operates with the file system. No need in any marks how to do that. Look at the example of fear, factoring, I'll show you a quick example of for factoring. 45. 07 Demo of Refactoring to a Testable Design: again before showing you their factoring process. I want to repeat that. If you want to fully understand their reasoning behind their factoring, take a look at my course, a p I n c. Shop of the best practices of design and implementation. Okay, let's go. First of all, it's apparent for me that there is a smell called primitive Obsession is hiding. The thing is that the record with parts has its own structure, which consists of four parts i d currency pair rate and stamp. So I'll allowed a class named the Record with Rid on the Properties. - Now I want to implement a file manager which will be responsible for formatting and all the logic it will implement the Ed quotation method. I also created the action in Admiration and Fi election structure to separate logic from IO operations. In the method, we have the pure logic which forms the record and tells the client what to do with the record. Now I want to implement the persisting file class file per sister takes the file path, get all records, reach the file and parses of I record glass, the apply action method performance in action, depending on a case. It adds a record Great new file or remove the file. The last entity I want to implement is the quotation service. This will be an orchestrator I exposed just for the sake of demonstration on Lee. One method at quotation. This method just delegates the responsibilities to appropriate objects. Now look, we don't need any marks. The quotation service and file manager we're going to cover by two or three integration tests. All the business logic related to passing and forming the records can easily be covered by unit tests. Let's write a couple of units lists. Here's the test I can write for the parsing string method. We also can write a test for the Ed quotation method of the file manager class. You can write it on your own. Treated as a homework. You can Donald the Source files and write a couple off unit tests on your own. In the next lecture, you learn how much discovered is enough 46. 08 How Much Test Coverage is Enough: beginners thrilled by the idea off unit testing sometimes start to think that they absolutely need to reach 100% coverage. So the question arises. Do we need to reach 100% coverage? If we're talking about inter prize software, then the short answer is no. Yes, indeed, it's a good idea to strive. Cover as much go this possible. But coverage by itself is not a goal. The goal is to create a safety net, making software more reliable and maintainable. By the way, all the rules off clean coding are also should be applied to tests when you ride them. Test gold has the same importance as the production code. Let's also reveal the difference between test coverage and reliability. Off software. 100% coverage doesn't guarantee that software is reliable and works correct, so we could state this. If you have a low coverage, it indicates that your code is not enough tested. If you have a high coverage, it indicates nothing. Yes, that are bad news. I agree, but this is the reality in which we leave. If you ask why test coverage doesn't mean anything, I'll show you an example. Look at these two code snippets. There is a synthetic method on the left, which checks if a value doesn't exceed some boundary. The method on the right tests the method on the left. Let's calculate the coverage metrics. All the lines are covered. It means that we have 100% code coverage here, but it doesn't mean that everything is tested. The Fools case is not tested, despite we have 100% coverage. So reaching 100% test coverage is a very hard and unnecessary undertaking, which you should avoid. It's a rule of thumb. 80% is the acceptable level off this coverage so stretched to keep the test coverage as close as you can to 80% If you have more than 80% covered, it's good for you off course if your tests are clean and have not been written just for the sake off, increasing the test coverage metric in the next lecture you learn, should you write tests for travel code 47. 09 Testing Trivial Code: the problem off testing Trivial code is related toe test driven design heavily, though it can be discussed without did it involved. The question is, should we write test for trivial properties with aimed togethers and centers or any equally trivial methods? And there are some different opinions even regarding this question, Robert Martin, a k Uncle Bob, initiated the most notable discussion, which was continued by Mark Semen in Shirt, the meaning Off the Uncle Bob's article regarding travel called Testing. Part of it can be distilled down to the following statements. Don't write tests for getters and setters. Those getters and centers will be indirectly tested by the tests off the other methods, so there is no point in testing them directly. Don't write tests for one line functions for functions that are obviously tree ville again , they will be tested indirectly. Uncle Bob states that TDD practices are not dogmas and off course he's right. Though his statements still required for the investigation, Mark Semen disagreed with Uncle Bob, saying that there are some problems related to uncle. Both statements they confused, cause and effect. Three Ville code may not stay tree ville, and it's horrible advice for beginners. The first question which comes to mind is how the hell properties and methods came into play without the failing test. TDD implies that we can't write code without having a failing test. Another concern is that very often practicing TDD. You don't know how much difficult the implementation will be. Another concern is that it might happen that, at this particular moment, a certain property street bill. But can you be sure that it will not be changed after a week, becoming a calculated property with its own logic of calculation, which obviously should be tested? In my opinion, it's hard to give a universal advice, which fits any possible cases. In my opinion, this problem belongs to one off many fundamental engineering problems which don't have easy answers. You must turn on your brain and deeply think about what you need and what you don't. What benefits do you see and what disadvantages you anticipate. Welcome to engineering. In the next lecture, you learn what test single concern rule means 48. 10 The Rule of Testing a Single Concern: you might hear the rule off a single assert protest, which literally states that you can write one and only one assertion in the unit test. This confuses beginners very much, since we very often find ourselves writing, multiple asserts, and we understand that we actually need to ride them in a single test. Let's clarify the rule off a single assertion. Here you can see the method which tests the properties off a glass money. I'm not going to show you the implementation, since it's irrelevant to our discussion. I'll just notice that this money class is suited for Russian currency, and it exposes two properties called a mountain kopecks and amount in rubles. In the US there are dollars and cents. We have rubles and coptics Accordingly. These tests creates the money object passing in a different amount off money expressed in Coptics and then verifies that properties return correct values. This test can be significantly simplified, but the idea is to show you that every time I create a new object, I have two assertions that check very close properties. It would be insane to create hundreds off unit test to test so close a P I members. The very important thing is that these assertions test very close things. They test the same concern, so the correct rule should sound us right. On the one logical assertion. It means that if several assertions share the same logical intention, they can be treated as a single logical assertion. And this is totally fine. Here's another example, which demonstrates a good example of multiple assertions these methods checks if several properties return correct values. In the case of the default configuration, it would be silly to create for different unit tests. If you write assertions for completely unrelated members by logic, then you violate the rule of a single assertion. And in such a case, you need to roll out separate unit tests. One assert protest really means test one aspect or behavior image test and communicated clearly in your test name. It doesn't literally mean that one test should have only one asserts statement in it, just one aspect or behavior. In one test and related aspect, behavior can be tested in another test. Sometimes we need more than one asserts statement toe assert one aspect or behavior, and it helps to add those assert statements in the test for better communication. In the next lecture, you learn much more on best practices off union testing 49. 11 More on Best Practices: Yes, we discussed in the lecture about guarantees provided by unit tests. No matter how many unit tests you have or how they're organized in the solution Explorer, they're not more than just needless baggage. If you can trust them, maintain them or read them, according to Roy Oshiro, that tests that you write should have a least three properties that together make them good trustworthiness. Developers will want to run trustworthy tests, and do you accept the test results with confidence? Trustworthy tests don't have bugs, and they test the right things. Maintain ability on maintainable Tests are nightmares because they can ruin project schedules or they may be sidelined. When the project is put on a more aggressive schedule. Developers will simply stop maintaining and fixing tests that take too long to change or that need to change very often on very minor production code changes irritability. This means not to just being able to read a test, but also figuring out the problem. If the test seems to be wrong without readability, the other two pillars full pretty quickly. Maintaining tests becomes harder and you can trust them anymore because you don't understand them. I'm going to create a separate course dedicated to best practices off union tests implementation. I want to keep my video courses short and concise, so I'll just only briefly mention some of the most important best practices. Avoid control flow operators strive to write unit tests that don't contain any switch if or else statements as well as any for each four or while Loops. Having control flow operators in a unit test is a smell, which shows that your unit test is too complex and most likely you need to reflector it into two or more tests. If you really need a loop, it should be encapsulated by some appropriate abstraction with a beautiful name, which explicitly reflects the intention or full the difficult stuff with hidden loops. Avoid the application. A sell rating said unit Tests are full fledged citizens off your code base. Developers avoid duplication in the production code base solving to do the same in unit tests. If you have some kind off repetitive logic, like setting up the salt in the same way in every test than consider writing and method decorated by a set up attribute provided by unit testing framework, use any slicker factoring techniques toe got the excessive code. Don't set up. There's doubles in the set up method. Please don't arranged as doubles in a set up method. Doing so will make it hard to read and made him the tests. My preference is to have each test create its own marks and stops by calling helper methods within the test so that the rear off the test knows exactly what's going on without needing to jump from test to set up. To understand the full picture, avoid order tests. There is one feature which is seemingly supported by any unit testing framework, which we haven't discussed and which I wouldn't recommend to use ever. It is Gold order tests. The meaning of this feature is pretty obvious from its name. It allows to run unit tests in a specific order. Why our order tests bad. Generally speaking, the thing is that any specific order creates the so called temporal coupling between unit tests. Temporal coupling is a well known smell, which you can face in a production called very often. In short, there is a temporal coupling between two functions. If the higher logic can change the order off their invocation thus ruining the business logic leading to embark. Actually, temporal coupling may look different in code. If you want to learn more about the smell, take my course. AP I insist shop the best practices of design and implementation. I am sorry. It may look like I'm trying to sell you another course, but if I add to this course old information from the course, this course will become excessively fat with a great number offside talks. Let's get back to the topic. So if you change the order, tests will fail. Most like every time you add a new test to a particular order, you need to think about when the test you want to add should run after test A or B or after just see and before deep. Another problem is that order tests are slower than a new ordered, since order tests cannot be run in parallel off course they can. They're ordered. Here is one of the eligible cases when you may want to rely on order tests. Previously, I worked with devices a lot at my work. I needed to write some tests for a device. That device couldn't process requests in parallel, so the parallel execution was impossible in the first place. Also, I needed to test the correctness off processing sequences of operations, so the necessity to right order tests was imposed by requirements off a project. Nothing else I could have done. And by the way, notice that, in my case, I wrote integration tests, not unit tests. Since, though, tests interacted with the device directly, I'm not aware of any riel cases when you absolutely need to right order the unit tests. But everything is possible, so I will not stay that there are no cases illegible for writing ordered unit tests. Just consider that order tests are hard to maintain and always think twice before relying on the feature. Off order tests over specification, sometimes especially beginners, full into the trap off over specification. Here are the waste to ride over specified unit tests. A certain purely internal state in an object under test. Use more than one mark in a single test. Use both stubs and marks in a single test. Asserts specific all orders or exact string matches when it's not required. Let's briefing discuss these points. First of all, the first smell is related to another problem when the internal state is at all visible to clients. This violates the encapsulation. Tests should not dig the internals of the system under test that they should test the visible A P I the second point using more than one mark in a single test. It's sometimes hard to avoid, but you should strive to, even if you need more than one mark. Usually the True unit test will set up only one of them. Other marks will behave themselves tentative regarding any calls. In a test where you test only one thing, which is, however, commanding right tests, there should be no more than one mark object. All other test doubles will act a Stubbs having more than one mark. Protest usually means you are testing more than one thing, and this can lead to complicated or brittle tests. The third point concerns mixing stubs and marks in a single test. This is also not always possible to avoid, but it's better to set up only one type of test doubles. Otherwise, a test would test too much in one run. Consider separating attest into two or more tests. The fourth point is my favorite one. I saw so many times tests that should test a specific returning value. But in addition, developers start to write assertions on Mark's verifying the sequence of calls arguments. Well, actually, this test should not bother buy all this stuff. The recipe is to separate interaction tests from tests that verify returning values and changes of state. I tried to achieve independency and isolation tests should not be dependent on each other. Put that in your pipe and smoke it. Often. Tests share some kind of object instance. In such cases, always rely on cleanup features off the testing framework in a new testing framework. As you've seen, you can write cleaning functions, decorating them by the following attributes. Tear down or one time to her down. Remember that the unit test runner can run unit tests in any order it likes. In the next lecture, you'll learn how to easily generate unit test names to save much time 50. 12 Generating Unit Test Method Signatures: It's very tedious to write the same declaration of a test math each time we live in a world off powerful ideas so we can make our life easier. Download the special visual studio code snippet file I attached to this lecture Close visual studio. If it is open and then go to the following path and copy that file, you don't loot it to this folder after that launch visual studio and tried to use the template hero quickly demonstrate how to use the template pile type, and Union Visual Studio discovers that it has such a code snippet. Then I'll press tab twice, and visual studio inserts the snippet where you should only replace the placeholders with appropriate names. Hi, type LA press tab Le Tab. Uh, when you're done, you pressed enter and the cursor will automatically jump to the beginning off. The test methods body very handy and saves a great amount of time 51. 13 Conclusion: congratulations. You finished the course. That was a long and interesting journey in this section. You learned that unit tests do not guarantee the success Bed unit tests become Have baggage , which you have to bear with you and maintain. In addition to the production code, that pragmatic unit testing concentrates on writing valuable unit tests. This is a moderate approach to unit testing that Singleton's and stated classes make impossible to write unit tests for the code, which is dependent on them. It's hard to replace. Stated dependence is that interfaces are not abstractions. It's a smell toe. Have a single implementation often interface. That 80% rate of test coverage is the minimum level you want to achieve. That testing trivial code might appear a useless undertaking. However, the things are not so simple. Trivial Cold sometimes transforms into something more complex that testing a single concern within a single unit test doesn't mean that you should avoid writing multiple calls to assertion methods. It means you should test only one logical unit in one unit test. If you learned this course carefully, then you know how to right Ron and Deb. OC unit tests right? Does doubles both manual and with a marking framework. How to apply to the Dean and avoid many mistakes while writing unit tests. Adhering to the best practices and how to use and unit for writing unit tests, You post a learned many other important things like different approaches to union. Testing the scores is only the beginning off your journey in unit testing Unit testing is a very complex topic, which requires much more details about special techniques off writing. Well, maintainable unit tests. I'm going to create an advanced unit testing course in the future. I attached great books related to union testing. Take a look at them. Thank you for watching.