SlideShare una empresa de Scribd logo
1 de 19
Unit Testing
TDD as a plus 
Anatomy of a Unit Test
• Unit tests give developers and testers a quick way to look for logic
errors in the methods of classes in Visual C#, Visual Basic, and Visual
C++ projects. A unit test can be created one time and run every time
that source code is changed to make sure that no bugs are
introduced.
• An unit is the smallest testable part of an application. An unit could
be an entire module, but is more commonly an individual function or
procedure. In object-oriented programing a unit is often an entire
interface, such as a class, but it could be an individual method as
well.
• Unit tests are created by developers or occasionally by testers during
the development process.
One more time
• Unit testing is not about finding bugs
• Unit tests, by definition, examine each unit of your code separately
Goal Strongest technique
Finding bugs (things that don’t work as
you want them to)
Manual testing (sometimes also
automated integration tests)
Detecting regressions (things that used to
work but have unexpectedly stopped
working)
Automated integration tests (sometimes
also manual testing, though time-
consuming)
Designing software components robustly Unit testing (within the TDD process)
(Note: there’s one exception where unit tests do effectively detect bugs. It’s when you’re refactoring, i.e.,
restructuring a unit’s code but without meaning to change its behavior. In this case, unit tests can often tell you
if the unit’s behavior has changed.)
Visual Studio unit test tools includes
• Test Explorer. Test Explorer lets you run unit tests and view their
results. Test Explorer can use any unit test framework, including a
third-party framework, that has an adapter for the Explorer.
• Microsoft unit test framework for managed code. The Microsoft unit
test framework for managed code is installed with Visual Studio and
provides a framework for testing .NET code.
• Microsoft unit test framework for C++. The Microsoft unit test
framework for C++ is installed with Visual Studio and provides a
framework for testing native code.
Visual Studio Unit Test projects
Microsoft Unit Testing Framework for C++
#include "stdafx.h"
#include <CppUnitTest.h>
#include "..MyProjectUnderTestMyCodeUnderTest.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
TEST_CLASS(TestClassName)
{
public:
TEST_METHOD(TestMethodName)
{
// Run a function under test here.
Assert::AreEqual(expectedValue, actualValue, L"message", LINE_INFO());
}
}
• Writing Unit tests for C/C++ with the Microsoft Unit Testing
Framework for C++
Microsoft Unit Test Framework for Managed
Code
// unit test code
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace BankTests
{
[TestClass]
public class BankAccountTests
{
[TestMethod]
public void TestMethod1()
{
}
}
}
• Creating and Running Unit Tests for Managed Code
Visual Studio Unit Test configuration
What to test
• Every public member of a class
• For each method you are testing you should include tests for the following:
• To confirm that the methods meet the requirements associated with them. Thus the test should verify that the
function does what it is supposed to do.
• To confirm the expected behavior for boundary and special values.
• To confirm that exceptions are thrown when expected.
• Unit tests should test one method only. This allows you to easily identify what failed if the test
fails.
• Unit tests should not be coupled together, therefore one unit test CANNOT rely on another unit
test having completed first.
• Units tests should use realistic data
• Unit tests should use small and simple data sets.
• How?
Isolating Code Under Test
• Isolate the code you are testing by replacing other parts of the
application with stubs or mocks.
• A stub replaces a class with a small substitute that implements the
same interface.
• To use stubs, you have to design your application so that each component
depends only on interfaces, and not on other components.
• Mocking is a very powerful tool that allows you to simulate
components in your unit environment and check how your code
operates within this environment.
• Mocking allows you to avoid creating Fake objects of any kind, and results in
fast executing code with a very high test coverage.
Dependency Injection (DI) approach
• Dependency injection (DI) is a technique for achieving
loose coupling between objects and their
collaborators, or dependencies.
• Rather than directly instantiating collaborators, or
using static references, the objects a class needs in
order to perform its actions are provided to the class
in some fashion.
• Most often, classes will declare their dependencies via
their constructor, allowing them to follow the Explicit
Dependencies Principle. This approach is known as
“constructor injection”.
• Methods and classes should explicitly require (typically
through method parameters or constructor parameters) any
collaborating objects they need in order to function correctly.
• Dependency injection is used a lot to make code more
testable.
class NeedsFoo
{
IFoo* foo;
public:
NeedsFoo(IFoo* foo) : foo(foo) { }
~NeedsFoo() { }
// Methods using the foo
};
[Export(typeof(INeedsFoo))]
[PartCreationPolicy(CreationPolicy.Shared)]
internal class NeedsFoo : INeedsFoo
{
[ImportingConstructor]
public NeedsFoo([Import]IFoo foo)
{
}
}
Good time to refactor code
public class DefaultAction : IActionResult
{
public DefaultAction()
{
_application = IoC.Get<IApplication>();
_inputService = IoC.Get<IInputService>();
}
}
One more
• Classes with implicit dependencies cost more to maintain than those
with explicit dependencies.
• They are more difficult to test because they are more tightly coupled
to their collaborators.
• They are more difficult to analyze for side effects, because the entire
class’s codebase must be searched for object instantiations or calls to
static methods.
• They are more brittle and more tightly coupled to their collaborators,
resulting in more rigid and brittle designs.
Unit test example (stub)
[TestMethod]
public void FillingFillsOrder()
{
var order = new Order(TALISKER, 50);
var mock = new MockWarehouse();
order.Fill(mock);
Assert.IsTrue(order.IsFilled);
Assert.AreEqual(TALISKER, mock.RemovedProductName);
Assert.AreEqual(50, mock.RemovedQuantity);
}
Unit test with Moq (.NET framework)
class ConsumerOfIUser
{
public int Consume(IUser user)
{
return user.CalculateAge() + 10;
}
}
[TestMethod]
public void TestConsume()
{
var userMock = new Mock<IUser>();
userMock.Setup(u => u.CalculateAge()).Returns(10);
var consumer = new ConsumerOfIUser();
var result = consumer.Consume(userMock);
Assert.AreEqual(result, 20); //should be true
}
Code Coverage
• To determine what proportion of
your project's code is actually being
tested by coded tests such as unit
tests, you can use the code coverage
feature of Visual Studio. To guard
effectively against bugs, your tests
should exercise or 'cover' a large
proportion of your code.
• Code coverage analysis can be
applied to both managed (CLI) and
unmanaged (native) code.
Test-Driven Development (TDD)
• Test-driven development (TDD) is a software development process
that relies on the repetition of a very short development cycle:
• requirements are turned into very specific test cases, then the software is
improved to pass the new tests, only.
• TDD is a software development process that relies on the repetition
of a very short development cycle:
• first the developer writes a failing test case that defines a desired
improvement or new function;
• then produces code to pass the test;
• and finally refactors the new code to acceptable standards.
TDD workflow
Links
• Verifying Code by Using Unit Tests
• Writing Great Unit Tests: Best and Worst Practices
• Mocks, Stubs and Fakes: it’s a continuum
• Test-driven development and unit testing with examples in C++
• Explicit Dependencies Principle
• .NET Moq framework. Quickstart
• Using Code Coverage to Determine How Much Code is being Tested

Más contenido relacionado

La actualidad más candente

How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit testEugenio Lentini
 
Refactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test AutomationRefactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test AutomationStephen Fuqua
 
Software Testing
Software TestingSoftware Testing
Software TestingAdroitLogic
 
Writing good unit test
Writing good unit testWriting good unit test
Writing good unit testLucy Lu
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated TestingLee Englestone
 
Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Hong Le Van
 
X unit testing framework with c# and vs code
X unit testing framework with c# and vs codeX unit testing framework with c# and vs code
X unit testing framework with c# and vs codeShashank Tiwari
 
An Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitAn Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitweili_at_slideshare
 
The Future is Now: Writing Automated Tests To Grow Your Code
The Future is Now: Writing Automated Tests To Grow Your CodeThe Future is Now: Writing Automated Tests To Grow Your Code
The Future is Now: Writing Automated Tests To Grow Your CodeIsaac Murchie
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestSeb Rose
 

La actualidad más candente (20)

Testing In Java
Testing In JavaTesting In Java
Testing In Java
 
Unit Testing 101
Unit Testing 101Unit Testing 101
Unit Testing 101
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit test
 
Refactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test AutomationRefactoring Legacy Web Forms for Test Automation
Refactoring Legacy Web Forms for Test Automation
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
Tdd & unit test
Tdd & unit testTdd & unit test
Tdd & unit test
 
Writing good unit test
Writing good unit testWriting good unit test
Writing good unit test
 
Presentation
PresentationPresentation
Presentation
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Unit testing with java
Unit testing with javaUnit testing with java
Unit testing with java
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
 
Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++
 
Testing in TFS
Testing in TFSTesting in TFS
Testing in TFS
 
Integration testing
Integration testingIntegration testing
Integration testing
 
X unit testing framework with c# and vs code
X unit testing framework with c# and vs codeX unit testing framework with c# and vs code
X unit testing framework with c# and vs code
 
An Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitAn Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnit
 
Write readable tests
Write readable testsWrite readable tests
Write readable tests
 
Nunit
NunitNunit
Nunit
 
The Future is Now: Writing Automated Tests To Grow Your Code
The Future is Now: Writing Automated Tests To Grow Your CodeThe Future is Now: Writing Automated Tests To Grow Your Code
The Future is Now: Writing Automated Tests To Grow Your Code
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under Test
 

Similar a Unit tests and TDD

Beginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBeginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBaskar K
 
Coldbox developer training – session 4
Coldbox developer training – session 4Coldbox developer training – session 4
Coldbox developer training – session 4Billie Berzinskas
 
Microsoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable CodeMicrosoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable CodeAleksandar Bozinovski
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@Alex Borsuk
 
Automated Software Testing Framework Training by Quontra Solutions
Automated Software Testing Framework Training by Quontra SolutionsAutomated Software Testing Framework Training by Quontra Solutions
Automated Software Testing Framework Training by Quontra SolutionsQuontra Solutions
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing FundamentalsRichard Paul
 
Unit testing basics with NUnit and Visual Studio
Unit testing basics with NUnit and Visual StudioUnit testing basics with NUnit and Visual Studio
Unit testing basics with NUnit and Visual StudioAmit Choudhary
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDDDror Helper
 
Test driven development
Test driven developmentTest driven development
Test driven developmentlukaszkujawa
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testingAdam Stephensen
 

Similar a Unit tests and TDD (20)

Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Beginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NETBeginners - Get Started With Unit Testing in .NET
Beginners - Get Started With Unit Testing in .NET
 
Testing Angular
Testing AngularTesting Angular
Testing Angular
 
Coldbox developer training – session 4
Coldbox developer training – session 4Coldbox developer training – session 4
Coldbox developer training – session 4
 
Unit testing
Unit testingUnit testing
Unit testing
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Unit Tesing in iOS
Unit Tesing in iOSUnit Tesing in iOS
Unit Tesing in iOS
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Microsoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable CodeMicrosoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable Code
 
Unit Tests with Microsoft Fakes
Unit Tests with Microsoft FakesUnit Tests with Microsoft Fakes
Unit Tests with Microsoft Fakes
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
 
Automated Software Testing Framework Training by Quontra Solutions
Automated Software Testing Framework Training by Quontra SolutionsAutomated Software Testing Framework Training by Quontra Solutions
Automated Software Testing Framework Training by Quontra Solutions
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
 
Unit testing basics with NUnit and Visual Studio
Unit testing basics with NUnit and Visual StudioUnit testing basics with NUnit and Visual Studio
Unit testing basics with NUnit and Visual Studio
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
TDD Workshop UTN 2012
TDD Workshop UTN 2012TDD Workshop UTN 2012
TDD Workshop UTN 2012
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
 

Más de Roman Okolovich

Más de Roman Okolovich (11)

C# XML documentation
C# XML documentationC# XML documentation
C# XML documentation
 
code analysis for c++
code analysis for c++code analysis for c++
code analysis for c++
 
Using QString effectively
Using QString effectivelyUsing QString effectively
Using QString effectively
 
Ram Disk
Ram DiskRam Disk
Ram Disk
 
64 bits for developers
64 bits for developers64 bits for developers
64 bits for developers
 
Virtual Functions
Virtual FunctionsVirtual Functions
Virtual Functions
 
Visual Studio 2008 Overview
Visual Studio 2008 OverviewVisual Studio 2008 Overview
Visual Studio 2008 Overview
 
State Machine Framework
State Machine FrameworkState Machine Framework
State Machine Framework
 
The Big Three
The Big ThreeThe Big Three
The Big Three
 
Parallel Programming
Parallel ProgrammingParallel Programming
Parallel Programming
 
Smart Pointers
Smart PointersSmart Pointers
Smart Pointers
 

Último

%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfonteinmasabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024VictoriaMetrics
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 

Último (20)

%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 

Unit tests and TDD

  • 1. Unit Testing TDD as a plus 
  • 2. Anatomy of a Unit Test • Unit tests give developers and testers a quick way to look for logic errors in the methods of classes in Visual C#, Visual Basic, and Visual C++ projects. A unit test can be created one time and run every time that source code is changed to make sure that no bugs are introduced. • An unit is the smallest testable part of an application. An unit could be an entire module, but is more commonly an individual function or procedure. In object-oriented programing a unit is often an entire interface, such as a class, but it could be an individual method as well. • Unit tests are created by developers or occasionally by testers during the development process.
  • 3. One more time • Unit testing is not about finding bugs • Unit tests, by definition, examine each unit of your code separately Goal Strongest technique Finding bugs (things that don’t work as you want them to) Manual testing (sometimes also automated integration tests) Detecting regressions (things that used to work but have unexpectedly stopped working) Automated integration tests (sometimes also manual testing, though time- consuming) Designing software components robustly Unit testing (within the TDD process) (Note: there’s one exception where unit tests do effectively detect bugs. It’s when you’re refactoring, i.e., restructuring a unit’s code but without meaning to change its behavior. In this case, unit tests can often tell you if the unit’s behavior has changed.)
  • 4. Visual Studio unit test tools includes • Test Explorer. Test Explorer lets you run unit tests and view their results. Test Explorer can use any unit test framework, including a third-party framework, that has an adapter for the Explorer. • Microsoft unit test framework for managed code. The Microsoft unit test framework for managed code is installed with Visual Studio and provides a framework for testing .NET code. • Microsoft unit test framework for C++. The Microsoft unit test framework for C++ is installed with Visual Studio and provides a framework for testing native code.
  • 5. Visual Studio Unit Test projects
  • 6. Microsoft Unit Testing Framework for C++ #include "stdafx.h" #include <CppUnitTest.h> #include "..MyProjectUnderTestMyCodeUnderTest.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; TEST_CLASS(TestClassName) { public: TEST_METHOD(TestMethodName) { // Run a function under test here. Assert::AreEqual(expectedValue, actualValue, L"message", LINE_INFO()); } } • Writing Unit tests for C/C++ with the Microsoft Unit Testing Framework for C++
  • 7. Microsoft Unit Test Framework for Managed Code // unit test code using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace BankTests { [TestClass] public class BankAccountTests { [TestMethod] public void TestMethod1() { } } } • Creating and Running Unit Tests for Managed Code
  • 8. Visual Studio Unit Test configuration
  • 9. What to test • Every public member of a class • For each method you are testing you should include tests for the following: • To confirm that the methods meet the requirements associated with them. Thus the test should verify that the function does what it is supposed to do. • To confirm the expected behavior for boundary and special values. • To confirm that exceptions are thrown when expected. • Unit tests should test one method only. This allows you to easily identify what failed if the test fails. • Unit tests should not be coupled together, therefore one unit test CANNOT rely on another unit test having completed first. • Units tests should use realistic data • Unit tests should use small and simple data sets. • How?
  • 10. Isolating Code Under Test • Isolate the code you are testing by replacing other parts of the application with stubs or mocks. • A stub replaces a class with a small substitute that implements the same interface. • To use stubs, you have to design your application so that each component depends only on interfaces, and not on other components. • Mocking is a very powerful tool that allows you to simulate components in your unit environment and check how your code operates within this environment. • Mocking allows you to avoid creating Fake objects of any kind, and results in fast executing code with a very high test coverage.
  • 11. Dependency Injection (DI) approach • Dependency injection (DI) is a technique for achieving loose coupling between objects and their collaborators, or dependencies. • Rather than directly instantiating collaborators, or using static references, the objects a class needs in order to perform its actions are provided to the class in some fashion. • Most often, classes will declare their dependencies via their constructor, allowing them to follow the Explicit Dependencies Principle. This approach is known as “constructor injection”. • Methods and classes should explicitly require (typically through method parameters or constructor parameters) any collaborating objects they need in order to function correctly. • Dependency injection is used a lot to make code more testable. class NeedsFoo { IFoo* foo; public: NeedsFoo(IFoo* foo) : foo(foo) { } ~NeedsFoo() { } // Methods using the foo }; [Export(typeof(INeedsFoo))] [PartCreationPolicy(CreationPolicy.Shared)] internal class NeedsFoo : INeedsFoo { [ImportingConstructor] public NeedsFoo([Import]IFoo foo) { } }
  • 12. Good time to refactor code public class DefaultAction : IActionResult { public DefaultAction() { _application = IoC.Get<IApplication>(); _inputService = IoC.Get<IInputService>(); } }
  • 13. One more • Classes with implicit dependencies cost more to maintain than those with explicit dependencies. • They are more difficult to test because they are more tightly coupled to their collaborators. • They are more difficult to analyze for side effects, because the entire class’s codebase must be searched for object instantiations or calls to static methods. • They are more brittle and more tightly coupled to their collaborators, resulting in more rigid and brittle designs.
  • 14. Unit test example (stub) [TestMethod] public void FillingFillsOrder() { var order = new Order(TALISKER, 50); var mock = new MockWarehouse(); order.Fill(mock); Assert.IsTrue(order.IsFilled); Assert.AreEqual(TALISKER, mock.RemovedProductName); Assert.AreEqual(50, mock.RemovedQuantity); }
  • 15. Unit test with Moq (.NET framework) class ConsumerOfIUser { public int Consume(IUser user) { return user.CalculateAge() + 10; } } [TestMethod] public void TestConsume() { var userMock = new Mock<IUser>(); userMock.Setup(u => u.CalculateAge()).Returns(10); var consumer = new ConsumerOfIUser(); var result = consumer.Consume(userMock); Assert.AreEqual(result, 20); //should be true }
  • 16. Code Coverage • To determine what proportion of your project's code is actually being tested by coded tests such as unit tests, you can use the code coverage feature of Visual Studio. To guard effectively against bugs, your tests should exercise or 'cover' a large proportion of your code. • Code coverage analysis can be applied to both managed (CLI) and unmanaged (native) code.
  • 17. Test-Driven Development (TDD) • Test-driven development (TDD) is a software development process that relies on the repetition of a very short development cycle: • requirements are turned into very specific test cases, then the software is improved to pass the new tests, only. • TDD is a software development process that relies on the repetition of a very short development cycle: • first the developer writes a failing test case that defines a desired improvement or new function; • then produces code to pass the test; • and finally refactors the new code to acceptable standards.
  • 19. Links • Verifying Code by Using Unit Tests • Writing Great Unit Tests: Best and Worst Practices • Mocks, Stubs and Fakes: it’s a continuum • Test-driven development and unit testing with examples in C++ • Explicit Dependencies Principle • .NET Moq framework. Quickstart • Using Code Coverage to Determine How Much Code is being Tested