Refactoring & Testability. Testing in OOP programming No life in flexible methodologies and for refactoring- infected developers without SOME kind of.

Slides:



Advertisements
Similar presentations
Unit Testing Australian Development Centre Brisbane, Australia.
Advertisements

xUnit Test Patterns (Some) xUnit Test Patterns (in practice) by Adam Czepil.
Spring, Hibernate and Web Services 13 th September 2014.
State of the Art Testability By Chad Parry. Background  The industry offers great advice on testability  Projects that follow that advice look different.
E-commerce Project Erik Zeitler Erik Zeitler2 Lab 2  Will be anounced and scheduled later  We will deploy Java Server Pages on a Tomcat server.
API Design CPSC 315 – Programming Studio Fall 2008 Follows Kernighan and Pike, The Practice of Programming and Joshua Bloch’s Library-Centric Software.
Design Issues. Where to put class definitions  What goes in a source file? At most 1 public class At most 1 public class Other “helper” classes as needed.
JUnit. What is unit testing? A unit is the smallest testable part of an application. A unit test automatically verifies the correctness of the unit. There.
Introduction to Refactoring Excerpted from ‘What is Refactoring?’ by William C. Wake and Refactoring: Improving the Design of Existing Code by Martin Fowler.
Software Testing. “Software and Cathedrals are much the same: First we build them, then we pray!!!” -Sam Redwine, Jr.
© S. Demeyer, S. Ducasse, O. Nierstrasz Chapter.1 Unit Testing Explained How to support changes? How to support basic but synchronized documentation?
12-Jul-15 Refactoring. 2 Refactoring is: restructuring (rearranging) code......in a series of small, semantics-preserving transformations (i.e. the code.
Software Testing & Strategies
Test-Driven Development “Test first, develop later!” –OCUnit.
Unit Testing Tips and Tricks: Database Interaction Louis Thomas.
By Bob Bunson  Simulation of software development project  Fictitious system from Concept to Code  Oriented around the.
Lecture 18 Page 1 CS 111 Online Design Principles for Secure Systems Economy Complete mediation Open design Separation of privileges Least privilege Least.
Testing. What is Testing? Definition: exercising a program under controlled conditions and verifying the results Purpose is to detect program defects.
CS378 - Mobile Computing App Project Overview. App Project Teams of 2 or 3 students Develop an Android application of your choosing subject to instructor.
STAR C OMPUTING Maker and I/O Model in STAR Victor Perevoztchikov.
CSC 213 – Large Scale Programming. Why Do We Test?
Designing For Testability. Incorporate design features that facilitate testing Include features to: –Support test automation at all levels (unit, integration,
Spring core v3.x Prepared by: Nhan Le. History v3.0 Spring Expression Language Java based bean metadata v3.1 Cache Abstraction Bean Definition Profile.
Introduction CS 3358 Data Structures. What is Computer Science? Computer Science is the study of algorithms, including their  Formal and mathematical.
Software Engineering 1 Object-oriented Analysis and Design Chap 21 Test-Driven Development and Refactoring.
17-Oct-15 Refactoring. 2 Refactoring is: restructuring (rearranging) code......in a series of small, semantics-preserving transformations (i.e. the code.
Junit At the forefront of Test Driven Development.
@DNNCon Don’t forget to include #DNNCon in your tweets! Effective Unit Testing for DNN James McKee Solutions Developer / Enterprise
Introduction CS 3358 Data Structures. What is Computer Science? Computer Science is the study of algorithms, including their  Formal and mathematical.
Dependency Injection Technion – Institute of Technology Author: Gal Lalouche - Technion 2015 ©
Башкирцев (Старовер) Станислав JavaTalks OOD Principles.
Refactoring1 Improving the structure of existing code.
Software Construction Lecture 18 Software Testing.
Computer Science 313 – Advanced Programming Topics.
Refactoring for Testability (or how I learned to stop worrying and love failing tests) Presented by Aaron Evans.
Using Mock Objects with Test Driven Development Justin Kohlhepp
Alternative Architectures: Inversion of Control Mike Hadlow mikehadlow.blogspot.com.
Exceptions, cont’d. Factory Design Pattern COMP 401 Fall 2014 Lecture 12 9/30/2014.
Magnus
Mock objects.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Scalatest. 2 Test-Driven Development (TDD) TDD is a technique in which you write the tests before you write the code you want to test This seems backward,
Software testing techniques Software testing techniques Software Testability Presentation on the seminar Kaunas University of Technology.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Testing Spring Applications Unit Testing.
(1) Test Driven Development Philip Johnson Collaborative Software Development Laboratory Information and Computer Sciences University of Hawaii Honolulu.
OOD teaches a complicated method, best for large systems. Here we teach the ten cent version. OO Design for the Rest of Us 1.
Refactoring1 Improving the structure of existing code.
Refactoring Agile Development Project. Lecture roadmap Refactoring Some issues to address when coding.
Automated Testing in Sakai Testing applications and services in isolation and in context Josh Holtzman, UC Berkeley David Haines, University of Michigan.
Testing JUnit Testing. Testing Testing can mean many different things It certainly includes running a completed program with various inputs It also includes.
L’origine dei mali: le dipendenze tra componenti Stefano Leli 14° Workshop DotNetMarche Venerdì 16 aprile
Dependency Injection with Guice Technion – Institute of Technology Author: Gal Lalouche - Technion 2016 ©
Beginning Software Craftsmanship Brendan Enrick Steve Smith
Test Isolation and Mocking Technion – Institute of Technology Author: Gal Lalouche © 1 Author: Gal Lalouche - Technion 2016 ©
Powerpoint Templates Page 1 Powerpoint Templates Unit Testing Ari Seppi
Software Engineering 1 Object-oriented Analysis and Design Applying UML and Patterns An Introduction to Object-oriented Analysis and Design and Iterative.
1 © Agitar Software, 2007 Automated Unit Testing with AgitarOne Presented by Eamon McCormick Senior Solutions Consultant, Agitar Software Inc. Presented.
Unit Testing - solid fundamentals
How to Write 3v1L, Untestable Code
Magento Technical Guidelines Eugene Shakhsuvarov, Software Magento
Unit Testing in a Team Sparkhound Presents by Steve Schaneville
History, Characteristics and Frameworks
Present by Andie Saizan, MCP
Improving the structure of existing code
Singleton Pattern Pattern Name: Singleton Pattern Context
Automated test.
Designing For Testability
European conference.
Computer Science 340 Software Design & Testing
Presentation transcript:

Refactoring & Testability

Testing in OOP programming No life in flexible methodologies and for refactoring- infected developers without SOME kind of AUTOMATED tests Tests are not a panacea, don't be categorical and skeptic. Tremendous use when possible to write JUnit is a tool, so "не забивайте гвозди штангенциркулем" Unit testing forces as to refactor!!!

Unit testing benefits (1 of 2) Can be applied to incomplete application JUnit is the first User of your code! Kinds of tests Unit->Integration->Function->Stress  Characteristic is the amount of application build already Makes me confident that I prevent my peer developers and QAs from finding tedious errors in my code. Less code to debug under test (as opposed to functional tests)

Unit testing benefits (2 of 2) Can simulate errors Test not only successful path (as integration test basically does), but the scenario when something can fail!  Testing exceptions Can act as a perfect and up-to-date documentation Encourage us for refactoring! Probably the most important advantage.

Example. Testing exceptions: try { methodWhichThrowsException(); fail(“Description”); } catch(ApplicationException meaningfulNameExpected) { assertNotNull(“Explanation why expected”,expected) }

Mocking Programming on interfaces vs. concrete classes Subclassing from concrete classes is a testing smell  If I subclass and override a method, what do I actually test? MockObjects.com (JMock) No! business logic. The mock should 100% comply to contract under CURRENT test. JMock is well suited for this rule.

Example: Testing service.

When to use mocks Notes on page 4

Too many mocks? Hard to setup a test? Mock lower OR refactor!  If a big framework has single but very smart method doWork() it's most likely a bad idea to test it Test may be skipped if the method's contract is based solely on other contracts

Example: Shopping cart test  (com.luxoft.tests.exercises.shoppingcart)

Refactoring Hardness to write (set up) unit tests FORCES us to simplify (factorize) the method or class or module.  Bad code is impossible to well unit test! there is one-to-one dependency between good code and ability to write good tests  Code smells (detect manually or by means of PMD, etc.)  Writing tests

Refactoring DON’Ts (1 of 3) Make Your Own Dependencies Heavy Duty Constructors Depend on Concrete Classes Conditional Slalom. if-branches and switch statements Depend on Large Context Objects Use Statics Use Global Flags

Refactoring DON’Ts (2 of 3) Use Singletons Everywhere Use Primitives Wherever Possible Look for Everything You Need (Law of Demeter) Couple functional code directly to the external systems it depends on Mix Object Lifecycles Side Effects

Refactoring DON’Ts (3 of 3) Create Utility Classes and Functions/Methods Create Managers and Controllers Do Complicated Creation Work in Objects Utils! Final Methods Handcuff your users to Specific Types Use static initializes

Example. Don’t depend on Large Context Objects: class Mechanic { Engine engine; Mechanic(Context context) { this.engine = context.getEngine(); }

Example. Violate the law of Demeter: class Monitor { SparkPlug sparkPlug; Monitor(Context context) { this.sparkPlug = context. getCar().getEngine(). getPiston().getSparkPlug(); }

Inversion of controls & objects construction Hollywood principle vs. factory method principle Collaboration graph and construction graph Remove new operators from application code as much as possible  Conclusion: separate classes with business logic and factories which create classes

Example. Avoid new op. for testability: class House { private final Kitchen kitchen = new Kitchen(); private boolean isLocked; private boolean isLocked() { return isLocked; } private boolean lock() { kitchen.lock(); isLocked = true; }

Benefits of IoC Allows us to mock in tests Allows us to use single instance of a class (saves us memory) Shortens the methods and make them more precise (only business logic).  Real isolation.

Inversion of controls. Conclusion It’s good both for tests and for code’s health to:  separate the business logic from factory code to create required objects (for that business logic) Doing so is really boring! Let the computer do boring stuff. Use IoC containers  Dependency injection (wiring)  Use empty, param-less constructors. Use setters!

Refactoring for testability. Final thoughts Consider IoC vs. factory method  Example: Isolate system resources getRemoteDataObtainer() Test coverage and test quality  100% coverage does not mean that the method is 100% tested. Example. Test quality measurement tools  Clover  Jester/Muclipse Oil detector in a car’s engine

When Unit tests are good? (1 of 2) Continuous and automated  Hudson / reports Fast, easy to run Written early to force Refactoring and detect design errors No real opportunity to use integration tests When code is good writing tests is fun. Should be easy

When tests are good? (2 of 2) When there a lots of tests!!! We MOCK a contract, i.e. believe that a mocked method follows the contract. Test that! Test as less code outside of the method under test as possible. Ideally:  test=(test_method_code) + (private_methods) + (mocks)

Unit tests is a must activity for a developer Unit tests are not even a way to test code, but for a developer is a very much a way to develop perfect code Just try!