SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot

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
 

What's hot (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 to 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 to 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
 

More from Roman Okolovich

More from 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
 

Recently uploaded

5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
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
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...software pro Development
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 

Recently uploaded (20)

5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
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
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 

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