Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Test Driven Development
Unit Testing, Dependency Injection, Mocking
1. A “best practice”
2. A software development process
3. An application of automated unit testing
What TDD is:
1. A replacement for integration testing
2. difficult to implement
3. a pain to maintain
What TDD is not:
● A 2005 study found that using TDD meant writing more tests and, in turn, programmers
who wrote more tests tended to be m...
pe·dan·tic
[puh-dan-tik]
adjective
1.
ostentatious in one's learning.
2.
overly concerned with minute details or formalism...
prag·mat·ic
[pragˈmatik]
adjective
1.dealing with things sensibly and realistically in a way that is based
on practical ra...
Questions to ask before adopting TDD4:
1. What are your projects’ short-term goals, and the long-term
goals for your organ...
1. Potentially increased development time on the front end.
a. Saves time during the maintenance phase when adding
functio...
Is it worth the time?8
TDD is a Software Development Process 5
(Re)write
a test
Did
it
fail?
Test
succeeds
Run
test
write
production
code
run
all...
A “unit test” is a method by which sets of one or more computer
program modules together with associated control data, usa...
The “Arrange-Act-Assert” Pattern
1. ARRANGE - set up everything needed for the test
2. ACT - call the code to perform the ...
Arranging the test can be done in several places
● ClassInitializeAttribute - this function decoration will mark a
functio...
Run the code to be tested, just as it would
normally be called.
This is how the test can supplement the
documentation by p...
Unit testing frameworks generally give a number of assertions that
can be used to validate test results.
Microsoft’s Frame...
Dependency injection is a software design pattern in which one or more dependencies (or
services) are injected, or passed ...
Single responsibility - a class should have a single responsibility
Open/closed principle - open for extension, closed for...
Constructor Injection
Namespace DependencyInjection
public class MainClass
IDependentClass _dependentClass;
public MainCla...
Setter/Property Injection
Namespace DependencyInjection
public class MainClass
public IDependentClass Dependency {get;set;...
Interface Injection9
Namespace DependencyInjection
public interface IDependentClass
void DoSomethingInDependentClass()
pub...
Mocking11
Mocking frameworks take advantage of dependency
injection to allow you to segregate the code under
test from its dependenc...
There are many mocking frameworks available, each
with their own pros and cons. FakeItEasy is one of
them.
FakeItEasy
You have a controller class, ThingController, that is using constructor
injection to get its DataContext class.
Your contr...
This presentation can be found online on SlideShare.
http://www.slideshare.net/mrjawright/test-driven-
development-3520033...
1.Erdogmus, Hakan; Morisio, Torchiano. "On the Effectiveness of Test-first Approach to Programming". Proceedings of the IE...
Upcoming SlideShare
Loading in …5
×

Test Driven Development:Unit Testing, Dependency Injection, Mocking

1,069 views

Published on

A presentation on Test Driven Development that delves into unit testing, dependency injection, and mocking with FakeItEasy.

Published in: Software, Technology
  • Be the first to comment

Test Driven Development:Unit Testing, Dependency Injection, Mocking

  1. 1. Test Driven Development Unit Testing, Dependency Injection, Mocking
  2. 2. 1. A “best practice” 2. A software development process 3. An application of automated unit testing What TDD is:
  3. 3. 1. A replacement for integration testing 2. difficult to implement 3. a pain to maintain What TDD is not:
  4. 4. ● A 2005 study found that using TDD meant writing more tests and, in turn, programmers who wrote more tests tended to be more productive.1 ● empirical studies at Microsoft and IBM have shown a drop in the defect density of between 40% and 90% for teams using test driven development.2 ● Unit tests are especially valuable as a safety net when the code needs to be changed to either add new features or fix an existing bug, since the sanity check for new changes. Since maintenance accounts for between 60 and 90% of the software life cycle, it’s hard to overstate how the time taken up front to create a decent set of unit tests can pay for itself over and over again over the lifetime of the project.3 ● Since every change requires regression testing you are more ensured that there will be no break in the production system. Essentially, TDD creates a harness in that it: (1) localizes defects, (2) detects unintended change, (3) improves developer confidence, and (3) decreases change risk. All these factors contribute to the overall reliability of your development when using TDD.4 ● TDD boosts a software development organization’s ability to rapidly respond to changing requirements by facilitating shorter development and integration cycles, and supporting the rapid refinement of new requirements.4 Best Practice
  5. 5. pe·dan·tic [puh-dan-tik] adjective 1. ostentatious in one's learning. 2. overly concerned with minute details or formalisms, especially in teaching. french: pédantesque Pedantic
  6. 6. prag·mat·ic [pragˈmatik] adjective 1.dealing with things sensibly and realistically in a way that is based on practical rather than theoretical considerations french: pragmatique Pragmatic
  7. 7. Questions to ask before adopting TDD4: 1. What are your projects’ short-term goals, and the long-term goals for your organization as a whole? 2. How does your team work individually and together? Is there open communication among team members? How open is your team to change? How open are you to change? 3. Are there immediate or long-term hurdles?Is a tight budget holding you back? Is your manager, or your manager’s manager skeptical about your ideas for the future? Does the administrative “red tape” often get you discouraged and cause stress and headache? Do you anticipate that there will be a change in management in the near future? Not For Everyone
  8. 8. 1. Potentially increased development time on the front end. a. Saves time during the maintenance phase when adding functionality or addressing bugs b. With time, the initial increase can be lessened as developers become more practiced at designing tests c. Standards can be put in place to help streamline the process 2. Code may be rushed to production without thorough testing because “the unit tests passed” a. stress that unit testing is not a replacement for integration and end-user testing. b. often bugs can be identified and fixed more quickly, allowing for more end-user QA Potential Concerns
  9. 9. Is it worth the time?8
  10. 10. TDD is a Software Development Process 5 (Re)write a test Did it fail? Test succeeds Run test write production code run all tests test(s) fail Refactor code test fails all tests succeed Repeat
  11. 11. A “unit test” is a method by which sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures are tested to determine if they are fit for use. The goal of unit testing is to isolate each part of the program and show that the individual parts are correct. Some benefits include: ● Identifies problems early in the development cycle ● Facilitates changes ● Simplifies integration ● Can supplement documentation Unit Testing 6
  12. 12. The “Arrange-Act-Assert” Pattern 1. ARRANGE - set up everything needed for the test 2. ACT - call the code to perform the action being tested 3. ASSERT - that the end result is as expected The Basics of Unit Testing
  13. 13. Arranging the test can be done in several places ● ClassInitializeAttribute - this function decoration will mark a function to be run immediately after the TestClass is loaded/before the first test is run ● TestInitializeAttribute - this function decoration will mark a function to be run before each test is run ● TestMethodAttribute - the test function itself Arrange
  14. 14. Run the code to be tested, just as it would normally be called. This is how the test can supplement the documentation by providing examples of how the code is used, and what the expected results are. Act
  15. 15. Unit testing frameworks generally give a number of assertions that can be used to validate test results. Microsoft’s Framework provides: ● AreEqual / AreNotEqual ● AreSame / AreNotSame ● IsFalse / IsTrue ● IsInstanceOfType / IsNotInstanceOfType ● IsNull / IsNotNull eg: Assert.IsNull(result); Assert.AreNotSame(expected, actual); Some frameworks, like NUnit, provide an interface for implementing custom assertions. Assert
  16. 16. Dependency injection is a software design pattern in which one or more dependencies (or services) are injected, or passed by reference, into a dependent object (or client) and are made part of the client's state. The pattern separates the creation of a client's dependencies from its own behavior, which allows program designs to be loosely coupled and to follow the dependency inversion and single responsibility principles. S.O.L.I.D - Single responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion Three Common Types: ● constructor injection - the dependencies are provided through a class constructor ● setter/property injection - the client exposes a setter method that the injector uses to inject the dependency ● interface injection - the dependency provides an injector method that will inject the dependency into any client passed to it. Clients must implement an interface that exposes a setter method that accepts the dependency Dependency Injection
  17. 17. Single responsibility - a class should have a single responsibility Open/closed principle - open for extension, closed for modification Liskov substitution - objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program, i.e. design by contract Interface segregation - many client-specific interfaces are better than one general-purpose interface. Dependency inversion - one should “Depend upon Abstractions. Do not depend upon concretions.” S.O.L.I.D Code10
  18. 18. Constructor Injection Namespace DependencyInjection public class MainClass IDependentClass _dependentClass; public MainClass(IDependentClass dependentClass) { _dependentClass = dependentClass; } public class Program public void Main(string[] args) IDependentClass dependency = GetCorrectDependency(); MainClass mainClass = new MainClass(dependency);
  19. 19. Setter/Property Injection Namespace DependencyInjection public class MainClass public IDependentClass Dependency {get;set;} public class Program public void Main(string[] args) IDependentClass dependency = GetCorrectDependency(); MainClass mainClass = new MainClass(); mainClass.Dependency = dependency;
  20. 20. Interface Injection9 Namespace DependencyInjection public interface IDependentClass void DoSomethingInDependentClass() public interface IInjectDependent void InjectDependent(IDependentClass dependentClass) public class MainClass :IInjectDependent IDependentClass dependentClass; public void DoSomething() public void InjectDependent(IDependentClass dependentClass) public Class DependentClass:IDependentClass public void DoSomethingInDependentClass() public class Program public void Main(string[] args) IDependentClass dependency = GetCorrectDependency(); MainClass mainClass = new MainClass(); ((IInjectDependent)mainClass).InjectDependent(dependency);
  21. 21. Mocking11
  22. 22. Mocking frameworks take advantage of dependency injection to allow you to segregate the code under test from its dependencies. By creating “mock” objects you can control the behavior of your code’s dependencies giving you more control and greater flexibility in designing your tests.
  23. 23. There are many mocking frameworks available, each with their own pros and cons. FakeItEasy is one of them. FakeItEasy
  24. 24. You have a controller class, ThingController, that is using constructor injection to get its DataContext class. Your controller will call the data context’s GetAllTheThings function, operate on the results, and return relevant data. To arrange your test with FakeItEasy: IEnumerable<IThing> mockResults = A.Fake<<IEnumerable<IThing>>; DataContext mockContext = A.Fake<IDataContext>(); A.CallTo(()=>mockContext.GetAllTheThings()).Returns(mockResults); ThingController tc = new ThingController(mockContext); IEnumerable<Thing> stuff = tc.GetTheThings(); A.CallTo(()=>mockContext.GetAllTheThings().MustHaveHappened(); You could also specify actual data for the return value, or parameters for the dependent call, and write asserts to validate the data returned by the controller. An Example
  25. 25. This presentation can be found online on SlideShare. http://www.slideshare.net/mrjawright/test-driven- development-35200336 Q & A
  26. 26. 1.Erdogmus, Hakan; Morisio, Torchiano. "On the Effectiveness of Test-first Approach to Programming". Proceedings of the IEEE Transactions on Software Engineering, 31(1). January 2005. (NRC 47445). Retrieved 2008-01-14. "We found that test-first students on average wrote more tests and, in turn, students who wrote more tests tended to be more productive." 2. http://research.microsoft.com/en-us/groups/ese/nagappan_tdd.pdf 3. Pros and Cons of Test Driven Development: http://www.particlewave.com/2013/05/13/pros-and-cons-of-test-driven-development/ 4. The Pros and Cons of TDD: http://www.pathfindersolns.com/archives/1684 5.http://en.wikipedia.org/wiki/File:Test-driven_development.PNG 6.http://en.wikipedia.org/wiki/Unit_testing 7/http://en.wikipedia.org/wiki/Dependency_injection 8.HTTP://XKCD.COM/1205/ 9.HTTPS://RICHNEWMAN.WORDPRESS.COM/ABOUT/CODE-LISTINGS-AND-DIAGRAMS/DEPENDENCY-INJECTION-EXAMPLES/DEPENDENCY- INJECTION-EXAMPLE-INTERFACE-INJECTION/ 10. http://en.wikipedia.org/wiki/SOLID_(object-oriented_design) 11.http://24fpsverite.com/wp-content/uploads/2013/03/french-taunting.jpg Sources

×