Poco Es Mucho: WCF, EF, and Class Design


Published on

See how POCO can be used from the Entity Mapping all the way to the client and how Unit Testing is made easier.

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Poco Es Mucho: WCF, EF, and Class Design

  1. 1. POCO es mucho:WCF, EF, and Class Design<br />Presented by Jamie Phillips<br />http://devblog.petrellyn.com<br />
  2. 2. Who is Jamie Phillips?<br />Senior Software Engineer with over 10 years experience in the Telecomm, e Commerce, Finance and Healthcare industries.<br />Passionate about working with the .NET framework and related technologies (C# 3.5, WCF, Entity Framework, etc.)<br />Natural ability to adapt to change has lead to becoming a practicing SCRUM Master and evangelist.<br />
  3. 3. Instances are lightweight – in as much as not being straddled with burdensome frameworks<br />Think of a WebForm class – not much use outside the context of ASP.Net<br />POCO classes can be used by everybody, without the worry of “dragging the baggage” of references across boundaries<br />POCO classes can be used in WCF and EF without conflicts on their implementation of Serialization.<br />What is so special about POCO?<br />
  4. 4. Specifically with WCF in .NET 3.5 SP1 you can serialize any C# object even if it doesn’t come with any serialization attributes. For example, the following CertificationType type was serializable by default:<br />What support for POCO was there before 4.0?<br />POCO(full)<br />POCO-less (pre 3.5 SP 1)<br />[DataContract]<br />public class CertificationType<br />{<br />[DataMember]<br />public int Id { get; set; }<br />[DataMember]<br />public string GoverningBody { get; set; }<br />[DataMember]<br />public string Title { get; set; }<br />[DataMember]<br />public DateTimeDateCertified { get; set; }<br />[DataMember]<br />public string Number { get; set; }<br />}<br />public class CertificationType<br /> {<br />public int Id { get; set; }<br />public string GoverningBody { get; set; }<br />public string Title { get; set; }<br />public DateTimeDateCertified { get; set; }<br />public string Number { get; set; }<br /> }<br />
  5. 5. Each layer of abstraction has its own definition of an entity to remove dependencies on specific frameworks; which requires translation from one form to another:<br />How was POCO affected outside of WCF?<br />privateCertificationTypeEntity Convert(CertificationTypecertificationType)<br />{<br />CertificationTypeEntityretVal = null;<br />if (certificationType != null)<br /> {<br />retVal = newCertificationTypeEntity();<br />retVal.DateCertified = certificationType.DateCertified;<br /> ...<br />retVal.Title = certificationType.Title;<br /> }<br />returnretVal;<br />}<br />
  6. 6. Typical Class Design without POCO<br />Client App<br />Client Specific<br />System.Runtime.Serialization<br />WCF Service<br />WCF Based<br />System.Data<br />.Objects<br />EFDM Context<br />EF Based<br />
  7. 7. Possible Class Design in EF 4.0<br />Client App<br />WCF Service<br />EFDM Context<br />POCO<br />
  8. 8. Pre 4.0 it was difficult to prepare decent unit tests because the EF Context could not be mocked. Areas of code remained “out of reach” from the unit tests:<br />What other benefits are there in 4.0?<br />public Diver GetDiver(int id)<br />{<br />DiveLoggerContext context = new DiveLoggerContext();<br />IQueryable<Diver> query = from diver in context.DiverSet<br /> .Include("CertificationTypes")<br /> .Include("DiveProfiles")<br /> .Include("DiveProfiles.DiveSite")<br /> .Include("DiveProfiles.WaterBodyType")<br /> .Include("DiveProfiles.AccessType")<br /> .Include("DiveProfiles.SurfaceType")<br />where diver.Id == id<br /> select diver;<br />return query.ToList().SingleOrDefault();<br />}<br />
  9. 9.
  10. 10. Unit Testing or Integration Testing?<br />Unit Tests:<br />test an individual unit of code in isolation<br />“stub out” or “mock” dependencies(e.g. DB, config files)<br />Integration Tests:<br />test “across code boundaries or architectural layers”<br />test as much of the code stack as feasibly possible(from UI to Data resource)<br />Most tests labeled as Unit Tests are actually Integration Tests.<br />
  11. 11. It is not a Unit Test if:<br />Communicates with a database<br />Communicates across a network<br />Interacts with the file systemE.g. reading / writing configuration files<br />Cannot run at the same time as any other unit test<br />Special “environmental considerations” required prior to runningE.g. editing configuration files, editing environment variables.<br />
  12. 12. How can true unit testing be achieved?<br />Through the application of Dependency Injection Pattern, “true unit testing” can be achieved for the majority of cases.<br />Wherever there is a need for using an external resource (including but not limited to Database, File System, etc.) a candidate for dependency injection exists.<br />Code refactoring is inevitable; think of it as the “cleansing pain” – once it is done, the healing can begin.<br />
  13. 13. What is Dependency Injection (DI)?<br />Dependency Injection is a design pattern based on the theory of “separation of concerns”.<br />An object instance will have its resource-based member variables (database connectivity, file system interaction, etc) [Dependency] set by an external entity [Injection]<br />Often referred to as IoC (Inversion of Control) – a common mistake made – IoC is a container/implementation of the Dependency Injection pattern.<br />
  14. 14. Types of Dependency Injection<br />Setter Injection<br />Class with no argument-constructor which creates the object with "reasonable-default“ properties. The user of the object can then call setters on the object to override these "reasonable-default“ properties.<br />public class LoggerService : ILoggerService<br />{<br />private IDiveLoggerContextm_context;<br />public LoggerService()<br /> {<br />m_context = new DiveLoggerContext();<br /> }<br /> public IDiveLoggerContext Context<br /> {<br />get { m_context = value; }<br /> }<br />
  15. 15. Types of Dependency Injection (cont)<br />Constructor Injection (Preferred)<br />Class needs to declare a constructor that includes everything it needs injected.<br />With Constructor Injection enforces the order of initialization and prevents circular dependencies<br />public class LoggerService : ILoggerService<br />{<br />private IDiveLoggerContextm_context;<br />public LoggerService()<br /> {<br />m_context = new DiveLoggerContext();<br /> }<br /> public LoggerService(IDiveLoggerContexti_context)<br /> {<br />m_context = i_context;<br /> }<br />
  16. 16. DI is only one half of the equation<br />Dependency Injection will facilitate better and truer Unit Tests, but it is not all that is needed.<br />In order to “mimic” the external dependencies mocking can be utilized.<br />Mocking can be achieved through the use of custom code or (more preferably) the use of a mocking framework.<br />
  17. 17. What is Mocking?<br />Mocking is only one pattern from four particular kinds of “Test Doubles”:<br />Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists.<br />Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production.<br />Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what is programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'.<br />Mocks are what we are talking about here: objects pre-programmed with expectations which form a specification of the calls they are expected to receive. <br />
  18. 18. How does this all fit in with EF?<br />In EF 1.0 the separation of concerns was a laborious task; without a mechanism of “disengaging” the Entity Framework to use a mocked repository, Dependency Injection was very crude at best.<br />By supporting POCO separation of concerns can easily be achieved in EF 4.0; the secret is in the use of IObjectSet<T><br />
  19. 19. How does this fit together?<br />Object Instances (class under test)<br />Mock Objects (injected dependency)<br />Dummy Data<br />
  20. 20. Now what?Identify Dependencies<br />Identify the dependencies that need to be injected.In EF 4.0 this will require creating an interface that exposes the entities as IObjectSet<T>:<br />public interface IDiveLoggerContext<br />{<br />IObjectSet<AccessType> AccessTypes { get; }<br />IObjectSet<CertificationType> CertificationTypes { get; }<br />IObjectSet<DiveProfile> DiveProfiles { get; }<br />IObjectSet<Diver> Divers { get; }<br />IObjectSet<DiveSite> DiveSites { get; }<br />IObjectSet<SurfaceType> SurfaceTypes { get; }<br />IObjectSet<WaterBodyType> WaterBodyTypes { get; }<br />
  21. 21. Now what?Create Default Class<br />The default class is the one that will really do the connectivity to the DB, sub classing from ObjectContext:<br />public class DiveLoggerContext : ObjectContext, IDiveLoggerContext<br />{<br />///<summary><br /> /// Initializes a new DiveLoggerModelContainer instance using<br /> /// the connection string found in the ' DiveLoggerModelContainer'<br /> /// section of the application configuration file.<br />///</summary><br />public DiveLoggerContext()<br /> : base("name=DiveLoggerModelContainer", "DiveLoggerModelContainer")<br /> {<br /> }<br />...<br />
  22. 22. Now what?Create IObjectSet<T> Properties<br />In each of the get properties, instantiate the instance of the IObjectSet<T> via the CreateObjectSet<T>() method:<br />private IObjectSet<CertificationType> _CertificationTypes;<br />public IObjectSet<CertificationType> CertificationTypes<br />{<br />get {<br /> return _CertificationTypes?? <br /> (_CertificationTypes= CreateObjectSet<CertificationType>());<br /> }<br />}<br />
  23. 23. Now what?Create Manager Class<br />The “manager” class will utilize the Dependency Injection pattern to permit “swapping” out of the identified interfaces:<br />public class LoggerService : ILoggerService<br />{<br />private IDiveLoggerContextm_context;<br />public LoggerService()<br /> {<br /> Initialize(null);<br /> }<br /> internal LoggerService(IDiveLoggerContexti_context)<br /> {<br /> Initialize(i_context);<br /> }<br />private void Initialize(IDiveLoggerContexti_context)<br /> {<br />m_context = i_context ?? new DiveLoggerContext();<br /> }<br />
  24. 24. Now what?Prepare for mocks<br />Use Extension method in Unit Test to “translate” List<T> of entities to IObjectSet<T> that will be used with the mocking framework:<br />public static class ObjectSetExtension<br />{<br />public static IObjectSet<T> AsObjectSet<T>(this List<T> entities)<br /> where T : class<br /> {<br /> return new MockObjectSet<T>(entities);<br /> }<br />}<br />
  25. 25. Now what?Writing the Test Method - Arrange<br />Avoid Record-Replay and use Arrange, Act, Assert (AAA) – it reflects what we do with objects.<br />Arrange – prepare all of the necessary actual and mock instances<br />// - ARRANGE -<br />// Create the stub instance<br />IDiveLoggerContext context =<br />MockRepository.GenerateStub<IDiveLoggerContext>();<br />// Create the out of range id<br />int id = -1;<br />// declare instance that we want to "retrieve"<br />Diver individual;<br />// Create a real instance of the Servcie that we want to put under test, injecting the dependency in the constructor<br />LoggerService service = new LoggerService(context);<br />// declare the expected Exception<br />Exception expectedExc = null;<br />
  26. 26. Now what?Writing the Test Method - Act<br />Act – by calling the method on the object under test to (later) verify it’s behavior:<br />// - ACT -<br />try<br />{<br /> individual = service.GetDiver(id);<br />}<br />catch (Exception exc)<br />{<br />expectedExc = exc;<br />}<br />
  27. 27. Now what?Writing the Test Method - Assert<br />Assert – that the actions performed yielded the desired result:<br />// - ASSERT -<br />// Make absoultely sure that the expected excption type was thrown<br />Assert.IsNotNull(expectedExc);<br />Assert.IsInstanceOfType(expectedExc, typeof(ArgumentException));<br />Assert.IsInstanceOfType(expectedExc, typeof(ArgumentOutOfRangeException));<br />// Make sure that the method was NOT called.<br />context.AssertWasNotCalled(stub => { var temp = stub.Divers; });<br />
  28. 28. Additional Features of Visual StudioCode Coverage<br />Another facet of Unit Testing is the analysis of code coverage.<br />Provides very good feedback on the areas of code that are being tested.<br />Does not tell you how reliable the code is.<br />Integrated with Visual Studio Ultimate Edition or Test Edition.<br />
  29. 29. Validate the Architecture of your modules in the IDE or in the Build<br />Additional Features of Visual StudioChecking Architectural Integrity with Layer Diagrams<br />
  30. 30. Questions and Answers<br />
  31. 31. Additional material<br />Dependency Injection and Mocking<br />
  32. 32. Which Unit Testing frameworks?<br />Comparisons between NUnit 2.x, MbUnit 2.4, MSTest and xUnit.net:http://www.codeplex.com/xunit/Wiki/View.aspx?title=Comparisons<br />NUnit<br />Command-line + UI<br />Open source currently at 2.4.8<br />MbUnit<br />Command-line + UI<br />Open source currently at 3.0.6<br />MSTest<br />Integrated with VS2008 Team or Test edition(can be run from command-line as well)<br />Code-coverage reporting integrated in Visual Studio<br />xUnit.net<br />Command-line<br />Open source currently at 1.1<br />
  33. 33. What Mocking frameworks are available for .NET?<br />NMock2<br />Licensed under BSD <br />Currently 2.0 RC (Jan 30, 2008)<br />Moq<br />Licensed under BSD <br />Currently 3.1.416 (Apr 16, 2009)<br />RhinoMocks<br />Licensed under BSD <br />Currently 3.5 RC (Oct 4, 2008)<br />TypeMock<br />Commercial product <br />Currently 5.3.0 (Jan 13, 2009)<br />
  34. 34. Comparison between RhinoMock, Moq, NMock2 and TypeMock<br />