SlideShare ist ein Scribd-Unternehmen logo
1 von 31
Using Entity Framework's New POCO Features: Part 2 (Unit Testing)  Presented by Jamie Phillips http://devblog.petrellyn.com
Who is Jamie Phillips ,[object Object],[object Object],[object Object]
 
Unit Testing or Integration Testing? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
The Restaurant Analogy: Unit versus Integration Tests (Roy Osherove)
It is  not  a Unit Test if: ,[object Object],[object Object],[object Object],[object Object],[object Object]
How can  true  unit testing be achieved? ,[object Object],[object Object],[object Object]
What is Dependency Injection (DI)? ,[object Object],[object Object],[object Object]
Types of Dependency Injection ,[object Object],[object Object],public class  Manager { IEFWorkshopContext _context; public Manager( ) { _context =  new  EFWorkshopContext(); } public  IEFWorkshopContext  Context { get  { _context =  value ; } } }
Types of Dependency Injection (cont) ,[object Object],[object Object],[object Object],public class  Manager { IEFWorkshopContext _context; public Manager( ) { _context =  new  EFWorkshopContext(); } public Manager( IEFWorkshopContext i_context) { _context = i_context; } }
DI is only one half of the equation ,[object Object],[object Object],[object Object]
What is Mocking? ,[object Object],[object Object],[object Object],[object Object],[object Object]
How does this all fit in with EF? ,[object Object],[object Object]
How does this fit together? ,[object Object],[object Object],[object Object]
Now what? Identify Dependencies ,[object Object],public interface  IEFWorkshopContext { IObjectSet<Address> Addresses {  get; } IObjectSet<Beer> Beers {  get; } IObjectSet<Brewery> Breweries {  get; } IObjectSet<SalesPerson> SalesPeople {  get; } IObjectSet<Person> People {  get; } IObjectSet<FavoriteBeer> FavoriteBeers {  get; } IObjectSet<Customer> Customers {  get; } IObjectSet<CustomerType> CustomerTypes {  get; } }
Now what? Create Default Class ,[object Object],public class  EFWorkshopContext : ObjectContext, IEFWorkshopContext { ///   <summary> ///  Initializes a new EFWorkshopEntities object using the ///  connection string found in the 'EFWorkshopEntities'  ///  section of the application configuration file. ///   </summary> public EFWorkshopContext()  : base( &quot;name=EFWorkshopEntities&quot;, &quot;EFWorkshopEntities&quot;) { } ...
Now what? Create  IObjectSet<T>  Properties ,[object Object],private  IObjectSet<Address> _Addresses; public  IObjectSet<Address> Addresses { get  { return _Addresses ??  (_Addresses = CreateObjectSet< Address>()); } }
Now what? Create Manager Class ,[object Object],public class  Manager { IEFWorkshopContext _context; public Manager() { Initialize(null); } internal Manager( IEFWorkshopContext i_context) { Initialize(i_context); } private void Initialize( IEFWorkshopContext i_context) { _context = i_context ??  new  EFWorkshopContext(); }
Now what? Prepare for mocks ,[object Object],public static class  ObjectSetExtension { public static  IObjectSet<T> AsObjectSet<T>( this  List<T> entities) where T : class { return new  MockObjectSet<T>(entities); } }
Now what? Writing the Test Method  - Arrange ,[object Object],[object Object],// - ARRANGE - // Create the stub instance IEFWorkshopContext  context = MockRepository .GenerateStub <IEFWorkshopContext>(); // Create the out-of-range id int  id = -1; // declare instance that we want to &quot;retrieve&quot; Person person; // Create a real instance of the Manager Manager manager =  new  Manager(context); // declare the expected Exception Exception expectedExc =  null;
Now what? Writing the Test Method - Act ,[object Object],// - ACT - try { person = manager.GetPerson(id); } catch  ( Exception  exc) { expectedExc = exc; }
Now what? Writing the Test Method - Assert ,[object Object],// - ASSERT - // Make absolutely sure that the expected exception type was thrown Assert .IsNotNull(expectedExc); Assert .IsInstanceOfType(expectedExc,  typeof ( ArgumentException )); Assert .IsInstanceOfType(expectedExc, typeof ( ArgumentOutOfRangeException )); // Make sure that the method was NOT called. context.AssertWasNotCalled(stub => {  var  temp = stub.People; });
Putting it together... ,[object Object]
Code Coverage ,[object Object],[object Object],[object Object],[object Object]
Demonstration on Code Coverage
DI oh my! ,[object Object],[object Object],[object Object],[object Object]
Questions and Answers
ADDITIONAL MATERIAL ,[object Object]
Which Unit Testing frameworks? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
What Mocking frameworks are available for .NET? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Comparison between RhinoMock, Moq, NMock2 and TypeMock Ease of use Cost Likes Dislikes Rhino Mocks Easy due to being strongly-typed, which makes the syntax great and &quot;safe&quot;. Free Strongly typed instancing - no need to use string references. Full  AAA  support Record / Replay should be implied not expected. Moq Doesn’t use record / replay scenarios! similar to Rhino Mocks Free Similar to Rhino Mocks, with no support for record / replay Creates wrapper of mock instance. NMock Use of strings to call property methods / normal methods. Free Pales to insignificance in contrast to RhinoMocks, Moq or TypeMock Need to use string declarations for instancing. Type Mock Extremely easy to implement mocking because it uses the .NET framework profiler API to monitor an application's execution.  Expensive The fact that it &quot;plugs-in&quot; to the CLR and captures type references, means that no code changes need to be done on legacy components. Prohibitively Expensive.

Weitere Àhnliche Inhalte

Was ist angesagt?

Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
Alex Borsuk
 
Dependency Injection Đ°Đ±ĐŸ Don’t call me, I’ll call you
Dependency Injection Đ°Đ±ĐŸ Don’t call me, I’ll call youDependency Injection Đ°Đ±ĐŸ Don’t call me, I’ll call you
Dependency Injection Đ°Đ±ĐŸ Don’t call me, I’ll call you
Dmytro Mindra
 

Was ist angesagt? (20)

Write readable tests
Write readable testsWrite readable tests
Write readable tests
 
EasyMock for Java
EasyMock for JavaEasyMock for Java
EasyMock for Java
 
Programmer testing
Programmer testingProgrammer testing
Programmer testing
 
Spring Certification Questions
Spring Certification QuestionsSpring Certification Questions
Spring Certification Questions
 
Mockito
MockitoMockito
Mockito
 
Junit, mockito, etc
Junit, mockito, etcJunit, mockito, etc
Junit, mockito, etc
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
 
L2624 labriola
L2624 labriolaL2624 labriola
L2624 labriola
 
Best practices unit testing
Best practices unit testing Best practices unit testing
Best practices unit testing
 
Enforce Consistentcy with Clean Architecture
Enforce Consistentcy with Clean ArchitectureEnforce Consistentcy with Clean Architecture
Enforce Consistentcy with Clean Architecture
 
Writing good unit test
Writing good unit testWriting good unit test
Writing good unit test
 
Selenium interview questions and answers
Selenium interview questions and answersSelenium interview questions and answers
Selenium interview questions and answers
 
Dependency Injection Đ°Đ±ĐŸ Don’t call me, I’ll call you
Dependency Injection Đ°Đ±ĐŸ Don’t call me, I’ll call youDependency Injection Đ°Đ±ĐŸ Don’t call me, I’ll call you
Dependency Injection Đ°Đ±ĐŸ Don’t call me, I’ll call you
 
Top 20 basic java interview questions for SDET
Top 20 basic java interview questions for SDETTop 20 basic java interview questions for SDET
Top 20 basic java interview questions for SDET
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
Code your Own: Authentication Provider for Blackboard Learn
Code your Own: Authentication Provider for Blackboard LearnCode your Own: Authentication Provider for Blackboard Learn
Code your Own: Authentication Provider for Blackboard Learn
 
Unit test
Unit testUnit test
Unit test
 
Dev labs alliance top 50 selenium interview questions for SDET
Dev labs alliance top 50 selenium interview questions for SDETDev labs alliance top 50 selenium interview questions for SDET
Dev labs alliance top 50 selenium interview questions for SDET
 
DevLabs Alliance Top 50 Selenium Interview Questions for SDET
DevLabs Alliance Top 50 Selenium Interview Questions for SDETDevLabs Alliance Top 50 Selenium Interview Questions for SDET
DevLabs Alliance Top 50 Selenium Interview Questions for SDET
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 

Ähnlich wie Ef Poco And Unit Testing

Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
Akhil Mittal
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docx
danhaley45372
 
Generic Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkGeneric Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity Framework
Akhil Mittal
 
éŠ™æžŻć…­ćˆćœ© &raquo; SlideShare
éŠ™æžŻć…­ćˆćœ© &raquo; SlideShareéŠ™æžŻć…­ćˆćœ© &raquo; SlideShare
éŠ™æžŻć…­ćˆćœ© &raquo; SlideShare
yayao
 
Coldbox developer training – session 4
Coldbox developer training – session 4Coldbox developer training – session 4
Coldbox developer training – session 4
Billie Berzinskas
 

Ähnlich wie Ef Poco And Unit Testing (20)

Entity Framework 4
Entity Framework 4Entity Framework 4
Entity Framework 4
 
Spring training
Spring trainingSpring training
Spring training
 
Elements of DDD with ASP.NET MVC & Entity Framework Code First
Elements of DDD with ASP.NET MVC & Entity Framework Code FirstElements of DDD with ASP.NET MVC & Entity Framework Code First
Elements of DDD with ASP.NET MVC & Entity Framework Code First
 
Entity Framework v2 Best Practices
Entity Framework v2 Best PracticesEntity Framework v2 Best Practices
Entity Framework v2 Best Practices
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
Jump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design PatternJump start to OOP, OOAD, and Design Pattern
Jump start to OOP, OOAD, and Design Pattern
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design Patterns
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
 
Overview of entity framework by software outsourcing company india
Overview of entity framework by software outsourcing company indiaOverview of entity framework by software outsourcing company india
Overview of entity framework by software outsourcing company india
 
MVC and Entity Framework
MVC and Entity FrameworkMVC and Entity Framework
MVC and Entity Framework
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docx
 
Dependency Injection and Autofac
Dependency Injection and AutofacDependency Injection and Autofac
Dependency Injection and Autofac
 
Generic Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkGeneric Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity Framework
 
Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4
 
éŠ™æžŻć…­ćˆćœ© &raquo; SlideShare
éŠ™æžŻć…­ćˆćœ© &raquo; SlideShareéŠ™æžŻć…­ćˆćœ© &raquo; SlideShare
éŠ™æžŻć…­ćˆćœ© &raquo; SlideShare
 
ASP.NET MVC3 RAD
ASP.NET MVC3 RADASP.NET MVC3 RAD
ASP.NET MVC3 RAD
 
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
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Coldbox developer training – session 4
Coldbox developer training – session 4Coldbox developer training – session 4
Coldbox developer training – session 4
 
Spring boot
Spring bootSpring boot
Spring boot
 

KĂŒrzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

KĂŒrzlich hochgeladen (20)

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

Ef Poco And Unit Testing

  • 1. Using Entity Framework's New POCO Features: Part 2 (Unit Testing) Presented by Jamie Phillips http://devblog.petrellyn.com
  • 2.
  • 4.
  • 5. The Restaurant Analogy: Unit versus Integration Tests (Roy Osherove)
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 26.
  • 28.
  • 29.
  • 30.
  • 31. Comparison between RhinoMock, Moq, NMock2 and TypeMock Ease of use Cost Likes Dislikes Rhino Mocks Easy due to being strongly-typed, which makes the syntax great and &quot;safe&quot;. Free Strongly typed instancing - no need to use string references. Full AAA support Record / Replay should be implied not expected. Moq Doesn’t use record / replay scenarios! similar to Rhino Mocks Free Similar to Rhino Mocks, with no support for record / replay Creates wrapper of mock instance. NMock Use of strings to call property methods / normal methods. Free Pales to insignificance in contrast to RhinoMocks, Moq or TypeMock Need to use string declarations for instancing. Type Mock Extremely easy to implement mocking because it uses the .NET framework profiler API to monitor an application's execution. Expensive The fact that it &quot;plugs-in&quot; to the CLR and captures type references, means that no code changes need to be done on legacy components. Prohibitively Expensive.

Hinweis der Redaktion

  1. Unit Tests are written to test an individual unit of code in isolation, “stubbing out” or “mocking” dependant resources that exist outside the domain of the code being tested (including but not limited to Database or Configuration Files) Integration Tests are written to test “across code boundaries or architectural layers”; they should test as much of the code stack as feasibly possible, from UI to Data resource.
  2. Imagine going to a restaurant with a bunch of your friends. there are some couples there as well as singles. At the end of the meal, it is time to pay. Unit testing is like giving a separate bill to each couple or individual. Each person knows only what they need to pay as well as tip, but do not care what anyone else had, or what the total meal amount is; as long as they pay what they need, they can go home peacefully. Integration testing is like giving one big check to the group, with everyone having to calculate on their own how much they need to pay. Sometimes everyone thinks that it works out, but in the end the total amount may be too high or too low. There is a lot of interaction going on to decide who pays for what and who has already paid. And often some will pay more for what they actually had than if they got their own individual bill.
  3. Dependency Injection is a design pattern based on the theory of “separation of concerns”. An object instance will have its resource-based member variables (database connectivity, file system interaction, etc) [ Dependency ] set by an external entity [ Injection ] Often referred to as IoC (Inversion of Control) – a common mistake made – IoC is a container/implementation of the Dependency Injection pattern.
  4. With Setter Injection it is not clear in which order things need to be instantiated and when the wiring is done
  5. Contrast the “Base” (Before) solution and the “UsingDi” (After) solution. Starting with the Manager classes, notice how the test methods call on the actual isntance of the Manager class and mock out the Dependency. Rhino Mocks works with AAA (Arrange, Act, Assert) so we setup the test and the expectations, call the method and assert the results.
  6. Executing a complete build we can view the code coverage results (using the “UsingDi” (After) solution)