Transcripts
1. Project Configuration: to set up the base project toe work along the war shop. You will need to clone the following project from Get Cub So first download and install Jabba J K Download and install Eclipse I D e Once in a clips, go to file import get folder project from Geet. Next clone you are I next again entered a u R I from the project or video description. You don't need a user passable here, so just click next. You can leave the fall settings and just click next until you click the finish bottom. Once the importance done, open the project. It is good to go to P O M XML. Right click Run us maven clean And then again, right Click Run us maven Install. Once you're ready, go to serves Test job A folder, Right click run US J unit test. So now all the test must be green with reference the main classes that you will start working on our the sale test glass on the order test glass
2. What is a Unit Test?: unit tests. Let's start by defining what is a unit test? A unit test. It's a piece of code written by a developer with a framework or library that we will call X unit. No, the word X unit. She'll be replaced by the name off the framework in your programming language. For instance, In Java, you may know this as J unit in PHP, it will be BHP unit, CPP unit for surplus bus and unit for the Nets by unit for python on so one for different programming languages. A unit test is an automated piece of code that will invoke part of the production code off the rial system that we will call unit of work. When we run this Tesco, it will execute the production code to validate a single assumption about its behavior. According to certain functionality, when you run the unit test, there are two possible outcomes that the desk fails or we can say red. In this case, the unit of work is not doing what the Tesco is suspected. Order. The test is successful or green. In this case, the unit of work is fulfilling and expectations of the unit test so What is this? Units of work? The unit of work under test is a single logical function off the use case in the system that can be involved by your public interface. A unit of war can be just a single method, whole class or multiple classes working together to achieve one single purpose that we want to verify. Commonly, you will have many unit tests to cover most of the cases off each unit of work. So what's the benefit off doing this at first sight? You might think that the benefit is to do some kind off Justine or Q A. But actually that is not the case. The real value for developers have in the production, called covert by unit tests, is that you can improve the coat. You will improve the called by doing re factoring and changes with confidence, because if you break some functionality while doing your changes, the test will tell you that something is no longer working so you can fix it. Therefore, you might want to cover the production code with multiple unit tests that you will run all together very, very often this test and sure that the court is working us intended after you change the code
3. Unit Test Example: unit test example. Let's take a look at an example off a unit test. Here you can see a class off the production code off point off sale system. Basically, this is a class called Fail, which has a property for the total amount of the sale. A constructor to create a sale with its total amount. A getter on a method called get change that returns the change that the customer must receive when pain in cash with certain amount. So how good you test that this method works properly. For instance, you can imagine that if there's a sale off 77 the customer base with 100 the method must return 23. Let's ride that us A test. So first, let's create a test class called sale test. Usually, there is a 1 to 1 relationship for every production class toe a test class that this class has the same name, but with the test word a specifics. In some occasions there may be a one to many relationship from one production, plus too many deaths glasses in a unit test. There are three sections. Arrange where you define, create or retrieve the objects that you will use for your test. In this case, we want to create a new sail with amounts off 77. The second section is called Act where You execute the actions that you want to test. In this case, we want to call. They get changed method with the parameter off 100 to indicate that the customer wants to pay with 100 on the last section is called 1/3 when we are firm that something happened US a result off the actions that were executed in this case, we want to affirm that the change calculated Waas 23. This three sections are known as the three ace Arrange Act assert. So now that we have our unit test, we can execute it. Let's say and unfortunately it's red. It's faded. What happened? Can you feel it out? Let's take a look at the production co again. So we see that the formula off this instruction in the get change method is incorrect. It should be the other way around. It'll be amount. Miners get total. Did you realize that before running the test, Maybe you did? Maybe not, And that's okay because we are humans on, especially when we're buildings things or doing visual inspections. We tend to be overconfident. So this is an example of how we can oversee something really simple and assume that it is correct until we test it. So do fix this method. We will rewrite this obstruction US amount. Miners get total. Now we're ready to run the test again on its ring. Now it works.
4. Good Unit Tests: FIRST: how to write good unit tests, and we referred to the corner him first to understand where we are with unit test, let's review at a high level the most important levels off test in at the highest level, you have the functional testing. That means testing a slice off functionality in the system that may interact with other dependencies to confirm that the cold is doing the right things according to the specifications. Here you does the system, asshole. Integration testing means that we are checking that different modules are working fine. One combined together us A. Group. The purpose off this level of testing is to expose false in the direction between integrated units that need to collaborate with each other. And finally, unit testing, where we want to test individual modules often application but in isolation. That means, without any interaction with actual dependencies, to confirm that the cold is doing things right. Unit testing is the developer responsibility to guarantee that they're called works? Well, what is a good unit test to describe and remember how a good unit tests. You look like we used the accordion first, where for each leather we have a word to remember certain characteristics. Fost a unit desk must run really fast. We are talking about milliseconds independent. Every unit test must be independent to each other and not depend on the results off other tests. Reputable test should be repeatable in any environment without variety in results. Self validating. No manual inspection is required to check whether the test has passed or failed. Thorough at this Moscow over every use case scenario, but not necessarily for 100% coverage. Let's take a look at each of these characteristics fast. A unit test must run really fast. We're talking about milliseconds. Remember that you will have thousands of tests in your project, so if there's low, you might feel reluctant to run them at. Developers shall not hesitate to run the test because they're slow on the country. They shall be comfortable with running all of them very frequently, like every few minutes independent. Some people may refer to these as isolated. Every unit test must be independent to each other. When you run a test, it must not affect the result off other tests. Test should not depend on the state off previous test, whether that is an object or monk metals. This allows you to run each desk individually when needed, which is likely to happen if a test fails, as you will want to Divac in tow. One method. Focus on scene what is going wrong and not have to run other tests. If you have a test that is checking or more defined some data, then that day does she will be created in the set up off the test are removed afterwards, so that's not affect the following test. Reputable deaths will be repeatable in any environment without variety. Results at that method should not depend on any data in the environment in which is writing . The results must be deterministic. There must be the same results every time on at every instance where they run. There should be no dependencies on date time or data that can be modified outside the test or random functions. Each desk shows it up or arrange its own data. If a set off test need some common data, you can use this top section in the test class for data within the test methods off one desk class or maybe some that the helper classes for reusability within many tests. Classes self validating A unit test must be automative. There should be no manual inspection required to check whether the test has passed or failed. A unit test must be transparent. Unexpressed intention off the author. In other words, it must be a leaving documents. When you read the name off the method in a test, you must understand what the system is able to do but us a difference with a static text. This is a document that can be executed on it will validate if that functionality is implemented on working correctly. Some people else also shade the S with small. As we've seen, the unit test must be small. That means that she'll only validate one unit off work without dependencies. Photo regarding coverage attest. Mask over every use case scenario, but not necessarily for 100% coverage atop you shall aim to test for corner edge and bond revalues death for large data sets in order to test run time and space complexity test for security with users have in different roles us. The expected behavior may be different based on different users. Royals does for large values, just overflow and under flow errors. For that, the types like integer terms for exceptions does legal arguments and bad inputs
5. Technical debt: Technical depth is caused by choosing an easy
and cheap solution. Now, instead of using a better approach that
will take longer, it is often the result
of using shortcut, quick fixes and patches rather
than full-scale solution. Daily caldera was originally used to refer to
flaws in the code, the sign of a software, but the concept can be applied
to any type of product. In some cases, solutions with technical depth might work
fine for a long time, but in many cases the
product may become unstable, insecure, or even dangerous. What is the first problem with technical depth
regarding productivity? A problem with technical
depth is that implies rework. First, we have the
time to implement these ISI but undesired solution with technical depth
at some point, it might be necessary
to implement it, right? So we have to add
the time to undo the easy solution on the time to implement
it in the right way. That process is also referred as Spain,
the technical depth. So as you can see, the total time and effort
used is a lot more than that. If we have a boy, the technical depth and implemented it correctly
from the beginning. Carrying technical VAB could be intentionally for
Bob or good reasons. Just like Guan can take financial depth to
gamble in a casino or to make your
business grow and pay the depth later
with a profit. For instance, lack
of professionalism, the team members are unprofessional or they don't
care about the product. Accumulated technical depth. The product has so much
technical depth that it seems impossible to implement
new features correctly. Time pressure, the team
is under time pressure, so the speed or released
is priority ties over the well-designed the
codes, lack of components. The team needs a spare part
for the product that is not available and they need
an alternative solution. Proof-of-concept
experiment or MVP. The team is doing a proof-of-concept or
MVP and prefers to deliver something with
technical depth to test the demand of the
product in the market, rather than building something technically perfect
that nobody wants. Technical depth can also
be unintentionally. For instance, lack of knowledge. The team members are two
junior and they don't know the best practices are the right design patterns
for the problems. New technologies, the team
is using a new technology or framework and he's not aware of the best
practices for it. When a team
continuously encourage technical depth
without paying it, it might cause several problems. Spaghetti code, they
internally sign of the product might become very messy and looked
like spaghetti code. And with high coupling, the product may be common, stable, dangerous, or insecure. The code becomes
harder and harder to understand and making changes or adding new features
require more effort and might easily break or other
existing functionalities, whether with a good solution or with more technical depth. Basically, dealing with a
cold ways becomes a pain. Hardware to pay. The more technical
depth is accumulated. The hardware to pay, it is just like unpaid monetary depth and
it's compound interest. Fake perception of
high velocity at team constantly encouraging
technical depth might look like very productive and
with a high velocity for some time because
of its quick solutions. But in the long term, the velocity will
drop because of the complexity and lack of
stability of the codebase. These can also
cause addiction by the stakeholders or product
owner to see fast deliveries. And Gould make hard duck
sat in their future, the high cost of
maintenance on fixing box. And furthermore, to
accept that the code is garbage and it needs
to be a refactor. The metaphor technical depth
was originally created by word canning gram to frame how to think about dealing
with this craft. To explain to his boss as an
analogy to financial depth, the extra effort
that it takes to add new features is the
interest paid on depth.
6. Design upfront and Emergent Design: up from the sign versus emergent design in support development. Big design up front. It's an approach in which the software this sign is to be completed. I'm perfected before the implementation. This is often associated with the water for model off software development. Actually, that sounds great, right? Well, only if you know in detail everything that you will need to build in advance, which nowadays is rarely the case. Change is inevitable. No matter how hard we try to predict the future, there always will be a lot of variables out of our control. Also, as you may know, Milton, the new software is the path to something new that must be discovered on the way. One of the principals off the agile manifesto is welcome change in requirements because while you walk the path off creating the new software, regular feedback will give you new ideas and requirements that will have been impossible to think in the beginning off the project. Therefore, we need the technique that help us to embrace the change and adapt are designed accordingly . So instead, off a big up from the sign. What we want is a design that gross organically at the sign that can adapt to changes on the marriage continuously. Emergent design focus on delivery in small pieces, off working cold with business value with emergent design. A development team started delivery in functionality on Let's the Design Emerge. Once someone told me in my previous company, we tried to do a merchant. The sign and we added cold and more called by the design did not emerge well off course not . It is not about just adding cold and one day that this sign will suddenly in marriage. This is a continues methodology that you have to apply every day. The design is mutating on emerging all the time in a merchant design. The development team will take a small piece off functionality and implemented use in Let's Practices and proper Discovery Ridge and then moved to the next functionality. They will see what dysfunctionalities have in common are a factor. L. A window designed to a marriage at the end Open Naja really cycle. The product has Onley small design just for the features released in this situation. The result is a simpler design which is easier to understand and maintain with less room for defects. Just driven development is a technique that can help us with emergency signs
7. Refactoring - What to refactor?: re factoring what to re factor technical depth. It's a concept in software development that reflects the cost of rework caused by choosing . And it's a solution instead of using a better approach that could take longer. The concept was originally invented by Ward Cunningham. US A. Metaphor. This metaphor help to explain, for instance, to managers why it is important to invest proper time in writing good software and re factoring. For instance, if you don't pay your credit card or monetary that you can accumulate interest and you will have to pay much more with so where is the same? If technical depth is not repaid, it can accumulate interest making. It's harder to implement changes and more expensive to maintain the application. Re factoring is a technique to improve the existing code without changing the functionality . In other words, you are improving the code but not providing any new value to the end user. The main value is for the developers. This is an investment so that the cold is more maintainable in the long term. This are two masterpieces to read about your factoring. The 1st 1 is the book by Martin Fuller, where he explained the techniques for re factoring on the 2nd 1 introduced how to refractor with solutions that include design patterns. So how do you know what you should were a factor? If you open the fridge on there is smell what it means. It means that something is rotting. So what would you do? I guess you will take it out if you leave it inside. Other food is going to run to with the code is the same. Sometimes you look at the cold and you are not sure why. But you know that something is not right, that something smelled bad. And if you don't change it or improve it, it will spread through all the code base Come back refers to these US code smells. The coat smells help you to identify what smells bad in the cold and usually factor. Some of the most important code smells are duplicated cold one of the most common cold smells. It is when there is identical or very similar code that exists in more than one location Long method, a method function or procedure that has grown too large. Large class A class that is Toler's feature M B A class that uses method off another class excessively in appropriate intimacy. A class that has dependencies on implementation details off another class refused to request a class that overrides a method off the base class in such a way that the contract off the base class it's not horn erred by the drive last. This is usually a violation to the Lisk of substitution principle. Lacey Class A class that does too little contrived complexity. Large usage off over like complicated the sign patterns where simpler design will suffice. As you may know, patterns are recording solutions to a problem that are proven that leads to good results. Anti patterns are the opposite. They are common solutions to a problem that for some free some people do and have negative consequences. When you see any anti pattern, you should re factor them. Let's mention some of them anemic. The main model is the use of the domain model without any business logic based in inheritance functionality from a utility class. Rather than use composition on delegation gold super requiring sub classes to call super class overrated and method circle ellipse problem. This is basically a bad use off subtype in circle our dependency. Unnecessary mutual dependencies between objects or modules. Constant interface. Usan interfaces to define constants, God object, concentrating too many functions in a single part off the design into one class object. Cecil Reusing objects Who state does not confirm the contract for re use. Object RG Failing to properly encapsulate objects permitting unrestricted access to their internals. Baltar gazed objects whose sole purpose is to pass information to another object. Sequential coupling a class that requires its methods to be called in a particle. Our order the your your problem A structure, for instance, off inheritance that is hard to understand due to excessive fragmentation.
8. Refactoring - How to refactor?: riff Factoring How to re factor. When you reflect her, you will need to change the cold toe. Apply good design principles. Let's mention some of them. Don't repeat yourself. Our first object oriented design principle is D. R Y. US named suggest Don't repeat yourself just means Tom Reid duplicate code. Instead, use obstruction to put common things in one place. The next ones are advices from the gang of force. The guys that wrote the book designed patterns. The 1st 1 is encapsulate. What varieties? Only one thing is constant in the software failed, and that has changed. So encapsulate the called that you expect to change in the future. Several design patterns use encapsulation. For instance, factory design pattern is one example. Off Encapsulation, which encapsulate object creation called UN. Provide flexibility to introduce new products later, with no impact on existing code programming to an interface, not implementation. This will lead toe flexible called, which can work with any new implementation off the interface in the future. So use interface, type on your valuables, properties return times and arguments favor composition over inheritance. Some of you may argue with this as many people think that there were using cold with inheritance. But I found that composition is lot more flexible than inheritance composition. Alos to change behavior off a class at runtime by said in a new object off a different implementation in a property that was declared us an interface type delegation principle. Don't do all the stuff yourself delegated to respective plus classical example of delegation principal are the equals and hash code methods in Java. In order to compare two objects for equality, we asked the other class itself to do the comparison instead of the client class. Doing that check benefit off. This design principle is no duplication of cold. I'm pretty easy to modify behavior. There are some designed principles called solid by Roberson Martin. There are very important single responsibility principle. A classroom always handled a single functionality and have only one purpose. This will increase. Cohesion already is coupling open clothes designed principal classes. Methods on function should be open for extension. Unclos for modification lis cub substitution principle. Given a super type subtypes moskvy substitute, I piss off the super type methods are functions which used the super class type must be ableto work with an object off a subclass without any issue interface segregation principle . This happened mostly when one interface contains many methods on a client only needs one dependency inversion. A class should depend on a fraction or interfaces on never to implementations. There are many re factoring techniques that are relatively easy to understand for most developers, usually most off the integrated development environments like Eclipse or Intelligent. They incorporate this re factoring techniques and automate involved changes. But you still have to take the decision. This is just list off the most important ones. Extract method. When you have a cold fragments that can be grouped together or is duplicated in many places , move this. Go to a separate new method and replace the old cold with a call to destructive method in lane method. When the method body is to all of use, replaced the calls to the method. With the methods content under lead, the method itself extract variable. When you have an expression that is too hard to understand, place the results off the expression in separate variables that are self explanatory. In line. Tamp When you have a temporary varietal that assigned the results off a single expression and nothing more replaced the references to the variable with expression itself movement off a method that makes more sense in another class done in its own class. Extract. Laugh when one class does the work off to create a new class on place the fields and methods responsible for the relevant functionality in it. In line class A class does almost nothing, and it's not responsible for any sin on no additional responsibilities. Our plan for it. Move all the features from the class to another class. Other well known re factoring techniques are Rene method at old removed parameter from a method bottom it dries. Method. Pull up a field method or constructor from subclass to a super class. Push down a field or method from a super class to a subclass, extract a super class or a subclass extract. The interface off the class that is called by many clients form template method on many others. So when you're a factor and you change the code, where is the safety net? It looks too dangerous to change the cold to improve it as there is the risk or breaking functionalities, or are the new box. So how can I riff actor with confidence At this point, you might realize what is the answer? The answer is unit test. You need to cover your called with unit test so there is no danger in re factoring and you can freely improve the cold on led the design an urge.
9. Introduction to Test Driven Development: test driven development introduction testers on developers are two very important roles in software engineering. They won't have complex responsibilities, but they also carry different mindsets. They often think differently. A developer need to sold problems with solutions that work on, typically will ask things like, What do I need to build? How shall I build it? How can I make it? Rob ist A tester needs to be in the shoes off the customer. A tester will ask things like, What can go wrong? How can I've read the application? How can I find witnesses? But developers still need to test. Some people may say, Well, I build a software, and if during the testing they find bugs, I can fix them Well, that is no diarrhea. Off course, we rely intestine to catch bags after development, but that coast a lot of rework and waste. So as developers, we have to make our best to provide Rub ist clean on back free software in a traditional approach. The developer will create the cold, and then there's that works correctly. But us we've seen once you build something is very difficult to impress the test in perspective. So what if we think off the testing before the developing. In that case, we will think off the test cases first and then implement called That passes the test does through in development, which we can refer. Toa us DDT. It's a software design and implementation technique included in the extreme programming methodology. Some out force will say that the name is somewhat unfortunate. Something like this sign, directed by examples, will have bean perhaps more appropriate. So we'll start by defining what DDT is not. Dignity is not a test in method or a Q A technique. DDT is not a Q A replacement. You are not trying to replace Q A or tester. With this. They are still very important in the silver development cycle. DDT is at the sign technique for emergent designs. Ditty East Test Before development You are looking to create the test first under an implement. The coat ditty are examples of what the system should do, and you can see these US A living specification. When you have a document, you can make a least off the things that the system can do, but you cannot prove it with dignity. You have a documentation off what the system can do, but you can also execute them on validated Testament. Development is related to the test first programming concept Off Extreme Program, in which began in the year 1999. Who are the famous people that supports DDT? Come back? Who is credited with having developed or rediscovered the technique stated in 2003. D activity. Encourage simple design UN Inspires confidence. Can Back is one of the creators off the agile methodology for software development known US Extreme Program in He also created together with Ari Gamma, the unit testing framework for Java J unit. He published many books, asked Small talk, Best practice patterns. Explanation off extra programming, test driven development by example. Planning extreme programming. Martine Fuller is an author and international speaker on software development, specializing in object oriented analysis and design patterns and agile software development methodologies, including extreme programming. He has a lot of publications, including a re factory and improvement of the sign off existing code. Eddie Gamma acted as leader off the development off the Eclipse platform. He was part of the Gang of Four that popularized the sign patterns. He was also the Creator J unit, along with Can back
10. TDD Development Cycle: just driven development development cycle. Let's take a look at the titty development cycle. You will start with the least off requirements. Usually they will be user stories. You will take one off this requirement on The first thing you will do is to write a TDD test for one off the functionalities off the story. You will not write any implementation off the phone finality yet, in other words, that is a test for a given functionality. But the system does not provide it. Now. You will run the desk on, make it fail. You want to make sure that this functionality is not a very level and you are moving in baby steps. Then you will ride the most simple possible called to pass the test. We only want to implement what is needed to pass the case off the test. You will not think generic to pass upcoming test or other cases not covered by this test. Once implemented, you run the test on making bus. On. The last step is re factor when you see at your solution and you see what you can improve or what you can re use without changed in the functionality next, you will think off a new test for another functionality off the same user story. Or when you are down with this user story, you can take another requirement to think off cases to write a new test you were. Repeat the cycle over and over, leading the design. Emerge constantly during the day until you go home. How long do you think one of this TDD cycle? She'll take one month, one week, one day, one hour. Well, the shorter the better, Like just a few minutes. So that means that you are working with very small steps. The titty development cycle is known us red, green refractor in red. You will write the test that fails for a functionality that does not exist. With this, you will make sure that they call that is written after the test will be testable. You will also Bali date this specification in green you cried the most simple called to pass the test. You will just fulfill the requirement and write the most simple solution that you can think off. You will not think off any fancy design pattern or any great design. At this point in re factor, you will concentrate on improving that. The sighing Here you will clean up the code. Remove repetitive cold, which is one of the worst coat smells. Think over using the code off previous functionalities. You will make sure that they called express its intention. You will remove every sin that smells bad like the code smells. You were a thing that assigned and apply good practices the sign, principles and designed patterns And of course, you will delete all unnecessary code.
11. Pros and Cons of TDD: cross and cons off TDD. What are the benefits off use entity? It provides a significant reduction of box. This investment off time can be translated into saving a lot of Q A time and avoid backs in production. You get a better design. That is a very reusable design with non rhythm them called with high cohesion. Low coupling on following the guidelines off clean code, the team has a better sense off trust and communication through the truth. Off the test. The test are an asset themselves. They are leaving specifications. They document what the system can do on. They can be executed to validate it. In the beginning, it go require effort. But in the long term, the team has a higher productivity. Maintain ability is easier under. There is a high level of confidence to make changes. What are the cons off use? Entity? It is difficult to use for integration tests. It is difficult for scenarios like user interface that the basis network external systems, five systems, especially legacy coat the support from the management. For a team that he's adopting, TDD is essential. The test are part of the cold base, and they require maintenance, too. You want to apply all the good design principles on the test coat as well. You will need to refractor the test as well, so that requires a time investment under could be a false sense of security. My group seen TDD is not a replacement for Q A on else, so you can have really good test on good test coverage. But you may not understand the requirements or miss in some except on criterias. In this chart, you can see the level off stress or chaos in a team or project along the time until a deadline with up from the sign. In the beginning, the stress is very low. Things seem to be going fine, but a soon ask you are near the deadline. Distress, unraced increase. Things may not work. A suspected many changes are required at the last minute, but changes take time on break other functionalities. So by the end of the project, the stress is very high. Which city in the beginning, the stresses high. Everything looks difficult on slow, but soon the project is going on. Changes become easier and fast integrating modules. It's not a big deal, and the team feels confident. When you are close to the release, things are in a good shape. Basically, with TDD, you are mitigating a lot of the risk. In the beginning. This chart compares devolution off the design principles along the time. In a project with up from the sign or test later, you start with a great designed that seems to cover all the possible cases in the future. But us long the time passes, the truth is different. New unexpected requirements appear on its hard to adapt their design. Therefore, all the design principles that you like and wish like high cohesion Low Coop ling, known repetitive, called reusability and others decreased considerably. With TDD, you start with small designs just for a few features, and you adopted the sign to add new features but always looking to fulfill good practices and design principles.
12. Sales System - Part 1: Total amount with discount: ditty example. Let's imagine that we're working on a sale system that is under development. There are many use their stories, and some of them were already developed usin TDD. We are required to implement one story use in test driven development. In this requirement, the seller wants to give a 10% discount to the price of the product when one buys five items or more unless the product is on sale, Let's get into it. We start with the Red Step off the test driven development cycle to write a test that fails . This is a project that is under development. There is already an order test class with unit test for the order class off the production , we will add and you matter to it to test that a discount will be applied. We write the three sections off a unit test in arrange with a fine that we will use a new order on the product hammer with the price of 20. In fact, we call the existing methods at I tempt toe odd five items off the product to the order on Finally in assert, we say that the discount was applied on the existing method get total were returned 90. Now we are ready to run this test on its face because our test expected 90 but the method get total returned 100. Let's take a look at the order class, which already exists in the system. There are some method get total that it rates over its order lines object on sums The sub total off each one a d n. It returns such some Let's take a look at the order line class. The meddled gets up. Total just returns the price of the product multiplied by the quantity in the order line. How we can implement the new functionality. You can think of many great solutions here, but let's just right the first simple thing that we can imagine. Now we are in the green step off the TDD cycle. We change the subtitle method, so if the quantity is greater done or equal to five, we return the price multiplied by the quantity and syrah 50.9. Otherwise, we just returned the price multiplied by the quantity. Now we can run the test on it pass. It's implemented. Now let's go to the re factor step are cold. Does not look right. We see that there is duplicated called with minor variations off the discount rate. Let's applied the extract local variable re factoring technique on this discount rate. Now we have a varietal discount rate initialized with one, but if the quantity is five or more, we changed it to syrup on nine. The previous cold is replaced with a reference to the new variable. Let's see if this broke something or not. We around the test on it pass.
13. Sales System - Part 2: Calculate Discount: Now we are back into the Red Step. The acceptance criteria off this story requires to calculate what was the discount that wa supplied. So we create a new desk method for this functionality called test order item discount. We create a new order on the product off price 20. We are five attempts off the product to the order on We say that the discount calculated was 10. So what do we do now? We should run the death, but we can't because they get this count Method does not exist in the order class. We just invented it in This test is good to combine TDD with programming by intention, with programming by intention, we think which method or responsibility and objects should have win Moke it on we created later. Let's create the new method. Get discount in the order class because we are in Red Step. We are not interested in its implementation. So we can just returned zero Now we can run the test and are suspected It fades The test expected Get discount to return 10 but return zero Let's make it bus. We have a test that expects 10 but our method is return in cereal. What is the most simple thing that we can do to pass the test? And when I say the most simple thing, I literally mean the most simple thing. We can just return 10 us. That is what the test is suspecting. Now we run the test on its green. I know that you may be thinking that look silly, but the idea entity is to make baby steps. So because we returned 10 we need to cover the functionality with other test case. If we will have implemented, get discount complete, we will miss the opportunity to test other cases in a real project with unit test, we want to cover many cases, including edge cases. But we want to start with a failing tests for each case. So we moved with baby steps. Maybe this makes more sense. With the next test from the tester point of view, we shall not trust that get this count works well just because it passes one test, we shall see how we can break it or what happened with other scenarios. For instance, we can create a test toe other six items off the product here. We respect that Get discount returned 12. We run the test on the first test passes, but the new one faced a suspect in 12. But get discount Returned 10. Yes, Get this count. Cannot fool us. So when you're in green, you must write the most stupid thing to pass the test. Actually toe full The test in red with on traffic code within it is suspicious and created . Test for new cases. We are enforcing proper implementation. How can we implement? They get this count method correctly. We can iterated the order lines off the order with programming. My intention. We assume that there is a method called get line discount. This method does not exist. So we have to create it and we create something simple. If the quantity is five or more, which has returned price might deployed by quantity and multiplied by Cira 50.1. Otherwise we return zero. We ran the test on the bus. Let's reflector! If we look at the code, it looks weird. There is repetitive code. Two methods have similar cold. So we can apply a struck local method to create a new method called get line total. We create the get line total method to return the price multiplied by quantity and update the other methods to call the new method. But not so fast. Let's run the test to make sure that this change works on its green. When we look again to the class, we see that gets up total and get lying. Discount our vote, calculating their discount rate but in different ways and get sub total. There's a multiplier for the total with 0.9 in get line. Discount is Syria 0.1, which is the same, but with a different perspective. This is also duplicated cold. We can apply a struck method to create a new method. Get this count rate we extracted, get discount rate us a new method and updated the references in gets up total and in get line discount US calls to the new method. We are ready. Use in the code to make sure that this is working on green. Were run the test, they get lying. Discount is working, but it's not easy to read. Another way to calculate the discount off the line. Cool V to deduct the sub total to the line total. We make such change our run the test to make sure it's works. You can think off more things to improve, but so far as you can see the order line class look much more simpler.
14. Sales System - Part 3: Product on sale: we're back into the Red step because we're going to handle products that are on sale. This requirement also says that if the product is on sale, no discount must be applied. Let's create a new test method in the order test class. Again, we create a new order on a new product. But using programming for intention, we assume a new parameter indicating that this product is on sale. Andi. Now this application does not handle the concept that the problem can be on sale. We buy five units off this product on in the Assert section with say that they get total returns 100 because there is no discount. We cannot run it yet because the product has not such constructor with the on say parameter yet. We created a new constructor in the product class, indicating that is on sale. Let's run the test on it failed because the discount was applied and get total returned 90 . There is the order line class with the method get discount rate that is being reused by other methods. What we can do to make the new test bus. Yes, we can change that if condition to check that the product is not on sale with programming. My intention, We assume that the product should have a method is on sale. We create. The method is on sale. In the product class, we run the test Hyundai Path. When we look at the brother class, what we can re factor. Although constructors are simple, the assignment off parameters to the properties is duplicated. We can call from one constructor to another for reuse when one creates a brother with just the name on the price. By the fault, we assume that the product is not on sale with a false parameter to make sure we're on the test on its green.
15. Hints and Recommendations for TDD: hints and recommendations. For TDD, the most important advice in test driven development is. Don't think you're right. They called early sign before, right in the test. Instead, think of examples of what the system should do and how will you test? I know it is difficult for developers when there is a problem. It is exciting the natural to think off classes, structures and patterns. But keep it step back and think of the test first. If you think of the design first, you will be doing some kind off small up front. The sign. I'm sure that you may come up with a structure that looks nice, but it may be an over design and harder to modify. Start with the test and trust that the process will surprise you with a great design that you could not have thought ahead with dignity. You will keep the designed, simple Onley for the problems that you are addressing right now. Remember that one of the principals off the agin manifesto is simplicity is essential. The art of maximising the amount of work not done entity. We want to give small steps that will help you to create a good coverage off test and only right. They called you need. So we will move in baby steps, for instance. If the test expect no just returned new in your production method? Yes, a stupid ass it sound. Then create another test. That s Bhagwan Tu minus one or the maximum integer value. We only want to design for the problems. I'm featured that we are addressing right now. If you program for more cases, the young the test you will exceed the simplicity and right cold that is less testable. Can you think off a definition off? Good coat. How will you compare Good code bears is bad code According to Michael Feathers called without test is bad code. It doesn't matter how well return it is. It doesn't matter how pretty or object oriented or well encapsulated it is with test We can change the behavior off our code quickly on verifiably Without them we really don't know if our code is getting better or worse In the industry legacy gold is often used us is long term for difficult to change cold that we don't understand. But Michael feathers are right with a different definition. Legacy code is simply called without test. You might think that this is severe, you may say. What about Klink owed? If a cold base is very clean and well structure, is that not enough? Well, let's not mix things well, Appling code. But it's not enough. A team takes high res when they make large changes without test. It's like doing aerial gymnastics without the net. It requires extraordinary skills.
16. Introduction to Test Doubles: Stubs and Mocks: death doubles marks on stops. Dignity is a bit more difficult with complex environment. Suppose that service manager is your competent and you need to test it. Ah, service manager calls a lot off external services If you use the rial services in your test , your test may be slow on the service corridor. Uninspected values that makes your tests nor reputable. For instance, your component may connect with a currency exchange, a p I that may return different values for the euro dollar currency every minute or maybe down or may throwing exception. What we want is a reputable test that takes control off the scenario. You want to see how production called behaves when the currency is 1.1 or 1.2, or if there is an arrow in the external service. What we can do is to use test doubles marks or staffs to replace the rial. Service marks and staffs are objects that we can create implementing the same interface as external service. But they are under our control, and we can simulate the scenarios that we want flying people into space percent interesting challenges to engineers and astronauts. One of the most difficult is how to make sure an astronaut is ready to go into space. A full integration test for the space shuttle will require being in space, and that, obviously, is not a safe way to test astronaut. That is why NASA has full simulators that mimic the surroundings off the space shuttle, which removes external dependency coming to be in outer space. An external dependency is an object in your system that you're cold under test, interact with over you have no control. Common examples are five systems threats, memory time and so on.
17. Test Double Strategies: this double strategies to replace the external dependencies. We used test doubles just like an actor that uses a double to replace him in action scenes . Some of the unit is double strategies. Are stops marks on being container testing stops are objects inserted up runtime into the object under test with dependency injection. This is in orderto isolate the color from the rial. Implementation marks are similar with the difference that they recorded called from the client objects and that you want to verify that your code perform specific calls to certain methods off the mark. Here we have a class that we want to test. That interacts with an external service which have an interface on its riel implementation that we use in production because we favour composition over inheritance and we are using dependency inversion our class hasta composition with the interface, it depends on the interface and not on the implementation. That's makes easy to create a new monk object or stuff us an implementation off the interface UN injected in run time to the object off the class on their test. Our unit tests will be similar to any unit test, with the difference that it will create a mock or stuff configure it un injected into the object off the class under test how to use stops, duty and execution off the test. The object under test invokes methods to the stop believing that is the real dependency. The stop just returns values that were configured for this test. When using the stuff, desert is performed on the class under test. The test treats the class under test like a black box. When using marks during the test, the object under test communicates with the mock object, and all the communication is recorded in the mark. In the assert, the test uses the mark object to verify that the desk passes. The test treats the class under test a bit more like a white books, checking how the direction with the service or Mark Washburn form from the object on their desk.
18. Stub Example: stub. Example. We will go back to the first example off the unit test off the sale system. We have a cell system with a user story to return the change to a customer. One pain in cash When we see the same class, it's very simple. There is a method get changed that receives the amount with what the customer is. Spain US A. Parameter on returns the amount minus the total off the sale. Now we have a union user study. As a customer, I want to see the total off the sale in other currency, pay in cash in other currency on get my change in some currency. But for now, we only need to cover euros on US dollars. At this point, the system does not handle any other currency than US dollars. Let's start with creating a desk for a simple case. The total sales is in U. S. Dollars. The customer pace in U. S. Dollars on the change is in U. S. Dollars. We create a new sale or 59 U. S. Dollars. We call the method get changed, indicating that the customer place with $100 on wants the change in U. S. Dollars, and we assert that the change is 41. But we cannot run the test yet because the same class has no currency. So we created a new constructor that we invented in the test with a parameter currency. And we are the new method get changed, indicating the amount the payment currency under changed currency. In this case, we can just return zero. We run the test on it fails what changes we can do to make the test pass. To implement this because the test suspect US dollars, we can just return the old method get changed. That was working for US dollars. We're on the test on his bus. Now let's create a new test for the case that the total is in U. S. Dollars, the customer paste with euros. I received the change in euros. We create a sail off 160 in U. S. Dollars. We call the get change method off the same, indicating that the customer paste with 200 euros unwanted change in euros. And finally we assert that the change calculated is 80. We run it on its face because the same class is still calculating in U. S. Dollars on returns 40. Here we see the interface off the currency exchange service. That is an external dependency. It has a method. Get currency that returns the currency exchange from one currency to another. There is a real implementation, but we want to create our own stuff. We go back to our test and we will use mosquito which is a framework to create staffs marks on other types. Off this doubles, we create a stub with a mock method The bus in the interface glass Asa parameter on we go figure to stop saying that when the method get currency is called with the parameters US dollars and euros, it must return 0.75. Then we inject the stop into the sale with the method set currency service on. We run the test but its face because we did not make any change to the cold off Get changed method yet how we can make the desk boss, we will implement something like this if the currency of the payment is different to the currency of the sale. We call the currency service to compare the total to the same currency of the payment on we returned the difference off the payment amount to the total comparative, and we run the test on its green. Can you tell what is wrong with this method? Well, you can tell that if the sale is in U. S. Dollars, the customer pace in euros. But once the chasing us dollars, this method will not work. But we don't want to cover that case now because we're doing baby steps. We need to create a test with such case. Make it fail. Unmake it bus. This is a quick comparison between stops and locks. A summary stops are much more simpler. And unless you have something very specific, you should prefer stops over marks.
19. Test Code Patterns: test code patterns. Gerard Massaro's Show Us What Are the Despot Turns and Best Practices for Unit Test. This is a summary off this. This is the least off this patterns. This Onley one thing. Usually that means one assert protest. Use one test class upper class under test on one test per feature. Never used more than one more protest, but many stops per test are fine. Eso prefer stops over marks. There are also at least off test males that will help you to identify when the tests cold is getting out of control. If you have Tesco duplication, you can use Perama tries, test or test utility. How the stable cold looks like with writing the test. First, we're in courage in to write testable cold. When you grade your solutions, you might consider doing a layered architecture, applying patterns off enterprise architecture under main driven design. Break the dependencies so you can test with stuffs or mocks by use independence injection. Apply the solid principles. Use program in by intention. Look out to write Cohasset coats and avoid global states. In the diagram, you can see how testable called usually looks like
20. Next steps: next steps. This are some next steps so you can practice DDT. Install a development environment for your programming language under correspondent X Unit Framework in Java, it will be Java Development Kid on Eclipse, which already includes their unit. These are simple steps that are described in their websites. But the best thing to exercise TDD is to do Caritas Did it take at us is the way to practice titty on Mastered the technique. Internet is full off site on blog's about TDD Qaida's some famous Get us to start our fist burst ball in and string calculator. I hope that you have enjoyed this curse on that It was helpful if you expected something that was missing. Please let me know. So I see how to improve or to compensate so I can get the best feedback for new Thank you