Design Patterns for MVVM Unit Testing & Testability Benjamin Day.

Slides:



Advertisements
Similar presentations
Design Principles & Patterns
Advertisements

Software Testing with Visual Studio 2013 & Team Foundation Server 2013 Benjamin Day.
Test-Driven Development José Almeida, Microsoft
Real World Scrum with TFS2013 Benjamin Day. Brookline, MA Consultant, Coach, & Trainer Microsoft MVP for Visual Studio ALM Team Foundation Server, Software.
How to be a C# ninja in 10 easy steps. Benjamin Day.
Lessons learned from developing a Windows 8 Metro application in C# Frode Nilsen Nilsen Labs Ticki.
Or How I Learned to Stop Worrying and Love the Binding Bryan Anderson.
Design for Testability: Mocks, Stubs, Refactoring, and User Interfaces Benjamin Day benday.com |
Team Foundation Server 2010 Builds: Understand, Configure, and Customize Benjamin Day benday.com |
(c) 2002 Object Mentor, Inc.1 Testing Things That Seem Hard To Test Robert Koss, Ph. D. ObjectMentor, Inc.
WCF RIA Services - Querying and Updating Data SILVERLIGHTSHOW.NET WEBINARS SERIES BRIAN NOYES, CHIEF ARCHITECT, IDESIGN INC 2 FEB 2011.
Real world Windows Phone development Igor
© 2014 HL7 ® International. Licensed under Creative Commons. HL7 & Health Level Seven are registered trademarks of Health Level Seven International. Reg.
User Group 2015 Version 5 Features & Infrastructure Enhancements.
N-Tier Architecture.
Test-Driven Development With Visual Studio 2005 Erno de Weerd Info Support.
Introduction to the Enterprise Library. Sounds familiar? Writing a component to encapsulate data access Building a component that allows you to log errors.
Design for Testability: Mocks, Stubs, Refactoring, and User Interfaces Benjamin Day.
10 Ways to Get Your Project Started Right Benjamin Day.
Presenter - Donn Felker.  Senior Consultant for Microsoft Gold Certified Partner- Statêra.  8 years of experience in developing and architecting enterprise.
@benday #vslive Better Unit Tests through Design Patterns: Repository, Adapter, Mocks, and more… Benjamin
Doing Something Useful with Enterprise Library 3.0 Benjamin Day Level: Intermediate.
@benday #vslive Automated Build, Test & Deploy with TFS, ASP.NET, and SQL Server Benjamin
MVC and MVP. References enter.html enter.html
Windows Azure Tour Benjamin Day Benjamin Day Consulting, Inc.
Building an Offline Smart Client using Domain-Driven Design Principles Tim McCarthy.
Top 7 Lessons From My First Big Silverlight Project Benjamin Day Benjamin Day Consulting, Inc.
Top 10 Ways to Go from Good to Great Scrum Master Benjamin Day.
Team Foundation Server 2012 Builds: Understand, Configure, and Customize Benjamin Day.
© ALEXANDRE CUVA  VERSION 2.00 Test Driven Design.
How to be a C# ninja in 10 easy steps Benjamin Day.
Alcatel-Lucent CDC Workshop, Coaching & Knowledge Transfer Architecture.
Refactoring for Testability (or how I learned to stop worrying and love failing tests) Presented by Aaron Evans.
Zero to Hero: Untested to Tested with Visual Studio Fakes Benjamin
The Start Menu……..Exposed What you never knew existed.
Overview of the MVVM pattern for Silverlight and WPF.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Testing Spring Applications Unit Testing.
04 |Sharing Code Between Windows 8 and Windows Phone 8 in Visual Studio Ben Riga
Real World SQL Server Data Tools Benjamin
Test Driven Development Introduction Issued date: 8/29/2007 Author: Nguyen Phuc Hai.
Model View ViewModel Architecture. MVVM Architecture components.
Modern Development Technologies in SharePoint SHAREPOINT SATURDAY OMAHA APRIL, 2016.
Windows 8 apps and the MVVM pattern SILVERLIGHTSHOW.NET WEBINARS SERIES GILL CLEEREN, October 16 th
Eliminate Team Build Headaches with Unit Tests, WiX and Virtualization Benjamin Day
Programming with MVVM Miguel A. Castro Architect -
Continuous Delivery and Team Foundation Server 2013 Ognjen Bajić Ana Roje Ivančić Ekobit.
Benjamin Day Get Good at DevOps: Feature Flag Deployments with ASP.NET, WebAPI, & JavaScript.
Benjamin Unit Testing & Test-Driven Development for Mere Mortals.
Presented by Alexey Vedishchev Developing Web-applications with Grails framework American University of Nigeria, 2016 Intro To MVC Architecture.
Beyond Basic Unit Testing: Mocks, Stubs, User Interfaces, and Refactoring for Testability Benjamin Day
Working in a Mobile App Development Environment Lesson 2.
Adam Schultz MVVM and WPF. MVVM Model, View, ViewModel A software architecture designed to separate out User Interface design, Business Logic, and Data.
TDD Unit tests from a slightly different point of view Katie Dwyer.
DevOps with ASP.NET Core and Entity Framework Core
Real world Windows Phone development
Better Unit Tests through Design Patterns: Repository, Adapter, Mocks, and more… Benjamin
Software Architecture & Difference from Design
Building Custom Workflows
Top 10 Mistakes in Unit Testing
Build Windows 10 UWP MVVM Apps with Prism
Entity Framework Core for Enterprise Applications
Unit Testing & Test-Driven Development for Mere Mortals
Unit Testing & Test-Driven Development for Mere Mortals
Get Good at DevOps: Feature Flag Deployments with ASP
Zero to Hero: Untested to Tested with Visual Studio Fakes
Unit Testing & Test-Driven Development for Mere Mortals
2/24/2019 © 2014 Microsoft Corporation. All rights reserved. Microsoft, Windows, and other product names are or may be registered trademarks and/or trademarks.
Entity Framework Core for Enterprise Applications
Implementing Security in ASP.NET Core: Claims, Patterns, and Policies
Tech Ed North America /6/2019 2:07 PM Required Slide
Presentation transcript:

Design Patterns for MVVM Unit Testing & Testability Benjamin Day

Consultant, Coach, Trainer Scrum.org Classes  Professional Scrum Developer (PSD)  Professional Scrum Foundations (PSF) TechEd, VSLive, DevTeach, O’Reilly OSCON Visual Studio Magazine, Redmond Developer News Microsoft MVP for Visual Studio ALM Team Foundation Server, TDD, Testing Best Practices, Silverlight, Windows Azure

Agenda My assumptions Super-fast overview  Model-View-ViewModel (MVVM)  Unit testing How to build stuff and test stuff.

Assumptions Automated tests are required for “done” Unit tests are written by developers. QA testing is different from developer testing. MVVM in Silverlight is harder than WPF  (My demos will be in Silverlight.)

Design for testability? Way of architecting your application Easy to write & run automated tests

Things that need to be architected. Requirement: design for testability Requirement: testability in isolation  They call them unit tests for a reason.  Helps to remember Single Responsibility Principle (SRP) In Silverlight, figure out async first.  Not planning for async will crush SRP.

SOLID Principles of Class Design PrinciplePurpose Single Responsibility Principle A class should have one, and only one, reason to change. Open Closed PrincipleYou should be able to extend a class’s behavior without modifying it. Liskov Substitution Principle Derived classes must be substitutable for their base classes. Interface Segregation Principle Make fine grained interfaces that are client specific. Dependency Inversion Principle Depend on abstractions, not on concretions.

Single Responsibility Principle Posters by Derick Bailey

Things that need to be tested. Goal: test your application without running the UI ComboBox / ListBox  Population of lists  Selection logic Field-based logic  Value, Visibility, Validation  Dependencies between fields MessageBoxes  Alerts and exceptions ProgressBar logic Model to Data Access ViewModel to Model

Overview of unit testing.

What is a Unit Test? Piece of code that verifies that another piece of code Test code verifies application code

What is Test-Driven Development (TDD)? Practice of developing code so that you always have proof that the code is working Mindset “Never write a single line of code unless you have a failing automated test.” -Kent Beck (“Test-Driven Development”, Addison-Wesley)

Why Write Unit Tests? High-quality code  Fewer bugs  Clean design  Clean code Professional Responsibility  Proof that your code works  Notification when your code is broken  Quality focus throughout the development cycle Side Effects  Code is easier to maintain, refactor  Self-documenting

Unit testing problems and solutions. Problems Extra code for the sake of the test Tons of setup code required to run the test User Interfaces  Best case: Hard to test  Worst case: Impossible to test Solutions Plan for testability Build a testable architecture Mocks & Stubs Dependency Injection Model-View-ViewModel

Plan for testability? If you build it, it needs to be tested. If you can test it with an automated test, it’s better. When you build, think of how to test it. The architecture changes when you think about how to test. It is important to remember the “Single Responsibility Principle”

So what is this MVVM thing?

Overview of MVVM.

What is MVVM? Model-View-ViewModel User interface interaction design pattern Cousin of Model-View-Controller (MVC) Enabled by data binding in WPF, Silverlight, WP7

Why use MVVM? …or MVC or MVP? Keep code organized Separate UI implementation from the logic Keep code out of the “code behind” (*.xaml.cs)  Hint: this enables Design for Testability

Our “To Do” list Architect the Silverlight Async solution Re-usable fields  Values, Visibility, and Validation List-based fields  ComboBox and ListBox MessageBoxes ProgressBars ViewModel to Model Model to Data Access

Tip: If you’re writing Silverlight, figure out your async solution early.

Network traffic in Silverlight It has to be async. If it isn’t, the UI thread locks…forever.

My initial client-side architecture.

My architecture after Async WCF beat me up and ate my lunch.

Async Kills Your Repository methods can’t return populated objects  must return void Exception handling is hard  Work happens on a different thread  Exceptions can’t “bubble up” the stack You could have your *.xaml.cs handle the callbacks  Ugly  Violates “separation of concerns”  Not very testable

Longer discussion of Silverlight async

My Solution: ReturnResult “Virtual” call stack Notify(Exception) or Notify(T)

The “glue” between method calls

Reactive Extensions for.NET Alternate Solution

Our “To Do” list Architect the Silverlight Async solution Re-usable fields  Values, Visibility, and Validation List-based fields  ComboBox and ListBox MessageBoxes ProgressBars ViewModel to Model Model to Data Access

Primitive Obsession in your ViewModel.

Primitive Obsession James Shore’s “Primitive Obsession”  Too many plain scalar values  Phone number isn’t really just a string  Validation in the get / set properties is ok but is phone number validation really the responsibility of the Person class?

Coarse-Grained vs. Fine-Grained Object Model James Shore blog entry talks about Responsibilities  Fine-grained = More object-oriented  Data and properties are split into actual responsibilities I’m concerned about  Responsibilities  Code Duplication  Simplicity

ViewModelField Provides common functionality for a property on a ViewModel

With & Without ViewModelField

Are your ViewModel properties Coarse or Fine? Fine-grained gives you room to grow ViewModelField Create custom controls that know how to talk to your ViewModelFields  Simplified binding expressions Add features later  Field validation later  Security

VIEWMODELFIELD Demo

COMBOBOX & LISTBOX Demo

MESSAGE BOXES Demo

PROGRESS BARS Demo

Our “To Do” list Architect the Silverlight Async solution Re-usable fields  Values, Visibility, and Validation List-based fields  ComboBox and ListBox MessageBoxes ProgressBars ViewModel to Model Model to Data Access

Focus your testing on stuff that tends to be buggy.

Calls to data access are buggy. The goal: Data access should take/return Model objects. Databases  ADO.NET objects don’t look like your Model  Make the db call, convert the data to Models  Take the Model, convert it to a db call WCF Services  Service Reference classes *are not* your model  Make a WCF call, convert the data to Models  Take the Model, make a WCF call This stuff is always buggy.

Repository & Adapter Patterns are your friend

What is Repository?

The Repository Pattern “Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects.”  Encapsulates the logic of getting things saved and retrieved

Synchronous Repository

Synchronous SQL Server & WCF

A Big Picture

What is Adapter?

Adapter Pattern “…converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.” from “Head First Design Patterns” by Elisabeth & Eric Freeman

My version of Adapter Pattern Take object of Type A and convert it in to object of Type B

Why are these patterns your friend? If you “Add Service Reference”, these are *NOT* your Models or ViewModels  (I know it might be tempting.)  (Remember, it’s 2 applications.) $0.02, you want your own Models and ViewModels  Breaks the dependency on the WCF services You’ll convert to/from the Service Reference objects

Why are these patterns your friend? Help focus your mind Better design Help contain bugs  These conversions to/from will be buggy Help localize change  Service endpoint designs will change often Unit test the conversions separately  (Remember it’s a “unit” test.)

Keep the Adapt separated from the Retrieve Two classes  Repository knows how to talk to the WCF service  Adapter knows how to turn the Service Reference types into Models Single Responsibility Principle (SRP)

REPOSITORY & ADAPTER demo

Our “To Do” list Architect the Silverlight Async solution Re-usable fields  Values, Visibility, and Validation List-based fields  ComboBox and ListBox MessageBoxes ProgressBars ViewModel to Model Model to Data Access

No shortcuts: Keep your ViewModels & Models separate.

It will be tempting to have your Repository/Adapter layer create ViewModels  (Don’t.) There’s a reason why it’s called Model-View-ViewModel

Why keep Model and ViewModel separated? ViewModel is a user interface design Model is the state of your application  aka. “Domain Model” pattern ViewModel advocates for the UI  1-to-1 between a ViewModel and a *.xaml file  Might reference multiple Models Don’t have the ViewModel fields directly update the Model.

It’s all about the Cancel button. If you’re “two way” data bound, How do you undo?

Cancel: ViewModel wraps Model ViewModel populates itself from the Model User edits the screen, ViewModel gets updated Model doesn’t get changed until Save button is clicked. Model is The Boss.

VIEWMODEL TO MODEL ADAPTER demo

Summary: Our “To Do” list Architect the Silverlight Async solution Re-usable fields  Values, Visibility, and Validation List-based fields  ComboBox and ListBox MessageBoxes ProgressBars ViewModel to Model Model to Data Access

Thank you. blog.benday.com | |

Other Resources

Other Resources

Other Resources