Dependency injection design pattern is introduced in order to solve some common issues due to explicit wiring between a component and its collaborator or service.
Spring Framework and AngularJS are involved to show how dependency injection could simplify the way of writing code but above all testing.
Clean and concise code is obtained using DI. Real example are provided on Github and Plunkr.
The presentation describes the properties of a good unit test. The code examples are written in java, but should make sense in each object oriented programming language.
You’re finally doing TDD, but your past mistakes are catching up with you. No matter what you do, you can’t get rid of the gaping black holes caused by your legacy code.
In this presentation, we learn about the causes of legacy code and the reasons it is so difficult to work with. Then we discuss various techniques to test untestable code, revive and simplify incomprehensible code, redesign stable yet untested code, and repair that rift we created in the time-space continuum.
Principles and patterns for test driven developmentStephen Fuqua
Developed to help introduce key topics in Test Driven Development, for new and veteran developers alike. Some examples are language-specific (C# / MSTest / Moq), but the principles apply to any object oriented language.
The presentation describes the properties of a good unit test. The code examples are written in java, but should make sense in each object oriented programming language.
You’re finally doing TDD, but your past mistakes are catching up with you. No matter what you do, you can’t get rid of the gaping black holes caused by your legacy code.
In this presentation, we learn about the causes of legacy code and the reasons it is so difficult to work with. Then we discuss various techniques to test untestable code, revive and simplify incomprehensible code, redesign stable yet untested code, and repair that rift we created in the time-space continuum.
Principles and patterns for test driven developmentStephen Fuqua
Developed to help introduce key topics in Test Driven Development, for new and veteran developers alike. Some examples are language-specific (C# / MSTest / Moq), but the principles apply to any object oriented language.
Refactoring Legacy Web Forms for Test AutomationStephen Fuqua
THE CHALLENGE:
Given you understand the value of test automation.
Given you are handed a legacy application to maintain and enhance
Given the application is in ASP.Net Web Forms
When you try to add tests
Then you find that test-driven development is literally impossible.
Stopping the Rot - Putting Legacy C++ Under TestSeb Rose
Presentation given at the ACCU 2011 Conference in Oxford, UK.
Case study of applying unit test to the DOORS codebase. Includes a quick overview of unit test & the Google Test and Mock libraries. Also 3 specific refactoring examples shown.
Join core JUnit 5 committer Sam Brannen to gain insight on the latest new features in JUnit 5 as well as what’s on the horizon.
In this presentation we will look at exciting new features that have been added in JUnit 5 over the past year, including temporary directories, custom display name generators, method ordering, timeouts, the Test Kit, and powerful new extension APIs. If you haven't yet made the switch from JUnit 4 to JUnit 5 you will definitely want to check out this presentation.
In closing, Sam will also provide a few tips on how to use JUnit Jupiter to test Spring and Spring Boot apps.
2015 JavaOne Java EE Connectors - The Secret Weapon ReloadedJonathan Gallimore
The Connector Architecture is one of the least well known and most underused parts of Java EE and often perceived as complicated. Yet this flexible and powerful API can be leveraged to integrate your application with just about any protocol or system. This session breaks through the complexities and explores the possibilities unlocked by key Connector improvements in Java EE 7. It explores simple but powerful real-world connectors—covering SSH, e-mail, and Twitter—that can be used in your own projects. It then presents a simple starter project to show how to build an in-bound connector backed by MDBs, connect to native clients, and employ advanced techniques such as using use CDI scopes for state. There is life beyond HTTP; live it.
Dependency injection in Java, from naive to functionalMarian Wamsiedel
The presentation contains more approaches to implement inversion of control (dependency injection). There is a naive implementation, a standard guice implementation and two functional solutions.
The code samples are available on a github repository.
Breaking Dependencies to Allow Unit TestingSteven Smith
Unit testing software can be difficult, especially when the software wasn't designed to be testable. Dependencies on infrastructure concerns and software we don't control are one of the biggest contributors to testing difficulty. In this session, you'll learn the difference between unit tests and other kinds of tests, how to recognize and invert dependencies, and how to unit test your code's interactions with these dependencies without testing the infrastructure itself.
Presented at FalafelCON 2014, San Francisco, September 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014FalafelSoftware
Unit testing software can be difficult, especially when the software wasn't designed to be testable. Dependencies on infrastructure concerns and software we don't control are one of the biggest contributors to testing difficulty. In this session, you'll learn the difference between unit tests and other kinds of tests, how to recognize and invert dependencies, and how to unit test your code's interactions with these dependencies without testing the infrastructure itself.
Refactoring Legacy Web Forms for Test AutomationStephen Fuqua
THE CHALLENGE:
Given you understand the value of test automation.
Given you are handed a legacy application to maintain and enhance
Given the application is in ASP.Net Web Forms
When you try to add tests
Then you find that test-driven development is literally impossible.
Stopping the Rot - Putting Legacy C++ Under TestSeb Rose
Presentation given at the ACCU 2011 Conference in Oxford, UK.
Case study of applying unit test to the DOORS codebase. Includes a quick overview of unit test & the Google Test and Mock libraries. Also 3 specific refactoring examples shown.
Join core JUnit 5 committer Sam Brannen to gain insight on the latest new features in JUnit 5 as well as what’s on the horizon.
In this presentation we will look at exciting new features that have been added in JUnit 5 over the past year, including temporary directories, custom display name generators, method ordering, timeouts, the Test Kit, and powerful new extension APIs. If you haven't yet made the switch from JUnit 4 to JUnit 5 you will definitely want to check out this presentation.
In closing, Sam will also provide a few tips on how to use JUnit Jupiter to test Spring and Spring Boot apps.
2015 JavaOne Java EE Connectors - The Secret Weapon ReloadedJonathan Gallimore
The Connector Architecture is one of the least well known and most underused parts of Java EE and often perceived as complicated. Yet this flexible and powerful API can be leveraged to integrate your application with just about any protocol or system. This session breaks through the complexities and explores the possibilities unlocked by key Connector improvements in Java EE 7. It explores simple but powerful real-world connectors—covering SSH, e-mail, and Twitter—that can be used in your own projects. It then presents a simple starter project to show how to build an in-bound connector backed by MDBs, connect to native clients, and employ advanced techniques such as using use CDI scopes for state. There is life beyond HTTP; live it.
Dependency injection in Java, from naive to functionalMarian Wamsiedel
The presentation contains more approaches to implement inversion of control (dependency injection). There is a naive implementation, a standard guice implementation and two functional solutions.
The code samples are available on a github repository.
Breaking Dependencies to Allow Unit TestingSteven Smith
Unit testing software can be difficult, especially when the software wasn't designed to be testable. Dependencies on infrastructure concerns and software we don't control are one of the biggest contributors to testing difficulty. In this session, you'll learn the difference between unit tests and other kinds of tests, how to recognize and invert dependencies, and how to unit test your code's interactions with these dependencies without testing the infrastructure itself.
Presented at FalafelCON 2014, San Francisco, September 2014
Breaking Dependencies To Allow Unit Testing - Steve Smith | FalafelCON 2014FalafelSoftware
Unit testing software can be difficult, especially when the software wasn't designed to be testable. Dependencies on infrastructure concerns and software we don't control are one of the biggest contributors to testing difficulty. In this session, you'll learn the difference between unit tests and other kinds of tests, how to recognize and invert dependencies, and how to unit test your code's interactions with these dependencies without testing the infrastructure itself.
Breaking Dependencies to Allow Unit TestingSteven Smith
Unit testing software can be difficult, especially when the software wasn't designed to be testable. Dependencies on infrastructure concerns and software we don't control are one of the biggest contributors to testing difficulty. In this session, you'll learn the difference between unit tests and other kinds of tests, how to recognize and invert dependencies, and how to unit test your code's interactions with these dependencies without testing the infrastructure itself.
Improving the Quality of Existing SoftwareSteven Smith
How do you improve the quality of your existing software, while continuing to add value for your customers? What are some heuristics and code smells you can look for, and principles and patterns you can use to guide you, as you make your software better over time instead of worse?
Patterns and practices for building enterprise-scale HTML5 appsPhil Leggetter
Developing large apps is difficult. Ensuring that code is consistent, maintainable, testable and has an architecture that enables change is essential. As is ensuring that multiple developers – across multiple teams – can efficiently contribute to the same application. When it comes to large server-focused apps, solutions to some of these challenges have been tried and tested. But, how do you achieve this when building HTML5 single-page apps?
In this session, Phil will cover the experiences his team have had when building HTML5 apps consisting of more than 250k lines of JavaScript (plus HTML templates, CSS, image, config etc) that are contributed to by multiple teams across multiple companies. He will highlight signs to watch out for as your HTML5 SPA grows, and a set of patterns and practices that help you avoid problems. He will also explain the simple yet powerful application architecture that their HTML5 apps have that is core to ensuring they scale.
Finally, Phil will demonstrate how tooling can be used to support these patterns and practices, and enable a productive developer workflow where the first line of code is feature code, features can be developed and tested in isolation, code conflicts are avoided by grouping assets by feature, and features are composed into apps.
Improving the Quality of Existing Software - DevIntersection April 2016Steven Smith
How do you improve the quality of your existing software, while continuing to add value for your customers? What are some heuristics and code smells you can look for, and principles and patterns you can use to guide you, as you make your software better over time instead of worse? How can we improve our skills and techniques so that writing high quality software becomes our default, fastest way of working?
Neoito — Design patterns and depenedency injectionNeoito
Dependency injection is a software design pattern that allows someone to remove hard-coded dependencies and makes it possible to change them. Dependencies can be injected to the object via the constructor or via defined method or a setter property.
Faiz Mohamed Haneef is currently the CEO and Chief Technology Architect at Neoito. He's a former Architect at Lowe's, Hallmark and Infosys.
SQL Injection is a dangerous vulnerability. The transformation from a normal SQL to a malicious query. The successful SQL injection attack can lead to unauthorized access, change or delete data, and theft of information. Do not take SQL injection for granted.
Building Front-End Web Apps that Scale talk from FED London at Yahoo! London.
Concepts and practices that fed into the workflows and application architecture that was core to the BladeRunnerJS toolkit.
This isn’t a talk about microservices, NO-SQL, Container solutions or hip new frameworks. This talk will show some of the standard Java APIs that are part of Java since version 5, 6, 7 or 8. All this features are very helpful to create maintainable and future-proof applications, regardless of whether JavaEE, Spring, JavaFX or any other framework is used. The talk will give an overview of some important standard concepts and APIs of Java like annotations, null values and concurrency. Based on an overview of this topics and some samples the talk will answer questions like:
- How can I create my own annotations?
- How can I create a plugin structure without using frameworks like OSGI?
- What’s the best way to handle NullPointerExceptions?
- How can I write concurrent code that is still maintainable?
How to Build Single Page HTML5 Apps that ScalePhil Leggetter
Developing large apps is difficult. Ensuring that code is consistent, well structured, tested, maintainable and has an architecture that encourages enhancement is essential. When it comes to large server-focused apps, solutions to this problem have been tried and tested.
But, how do you achieve this when building HTML5 single page apps?
In this talk we’ll cover the signs to watch out for as your HTML5 SPA grows and provide examples of some of the tooling types that can contribute-to as well as ease the growing pains. Finally, we’ll demonstrate how tooling can be used to support a set of conventions, practices and principles that enable a productive developer workflow where the first line of code is feature code, features can be developed in isolation, code conflicts are avoided by grouping assets by feature and features are composed into apps.
The demonstrations will use BladeRunnerJS, an open source developer toolkit written in Java, but the concepts are widely applicable.
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
Les Buildpacks existent depuis plus de 10 ans ! D’abord, ils étaient utilisés pour détecter et construire une application avant de la déployer sur certains PaaS. Ensuite, nous avons pu créer des images Docker (OCI) avec leur dernière génération, les Cloud Native Buildpacks (CNCF en incubation). Sont-ils une bonne alternative au Dockerfile ? Que sont les buildpacks Paketo ? Quelles communautés les soutiennent et comment ?
Venez le découvrir lors de cette session ignite
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Globus
The U.S. Geological Survey (USGS) has made substantial investments in meeting evolving scientific, technical, and policy driven demands on storing, managing, and delivering data. As these demands continue to grow in complexity and scale, the USGS must continue to explore innovative solutions to improve its management, curation, sharing, delivering, and preservation approaches for large-scale research data. Supporting these needs, the USGS has partnered with the University of Chicago-Globus to research and develop advanced repository components and workflows leveraging its current investment in Globus. The primary outcome of this partnership includes the development of a prototype enterprise repository, driven by USGS Data Release requirements, through exploration and implementation of the entire suite of the Globus platform offerings, including Globus Flow, Globus Auth, Globus Transfer, and Globus Search. This presentation will provide insights into this research partnership, introduce the unique requirements and challenges being addressed and provide relevant project progress.
A Comprehensive Look at Generative AI in Retail App Testing.pdfkalichargn70th171
Traditional software testing methods are being challenged in retail, where customer expectations and technological advancements continually shape the landscape. Enter generative AI—a transformative subset of artificial intelligence technologies poised to revolutionize software testing.
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
Accelerate Enterprise Software Engineering with PlatformlessWSO2
Key takeaways:
Challenges of building platforms and the benefits of platformless.
Key principles of platformless, including API-first, cloud-native middleware, platform engineering, and developer experience.
How Choreo enables the platformless experience.
How key concepts like application architecture, domain-driven design, zero trust, and cell-based architecture are inherently a part of Choreo.
Demo of an end-to-end app built and deployed on Choreo.
Understanding Globus Data Transfers with NetSageGlobus
NetSage is an open privacy-aware network measurement, analysis, and visualization service designed to help end-users visualize and reason about large data transfers. NetSage traditionally has used a combination of passive measurements, including SNMP and flow data, as well as active measurements, mainly perfSONAR, to provide longitudinal network performance data visualization. It has been deployed by dozens of networks world wide, and is supported domestically by the Engagement and Performance Operations Center (EPOC), NSF #2328479. We have recently expanded the NetSage data sources to include logs for Globus data transfers, following the same privacy-preserving approach as for Flow data. Using the logs for the Texas Advanced Computing Center (TACC) as an example, this talk will walk through several different example use cases that NetSage can answer, including: Who is using Globus to share data with my institution, and what kind of performance are they able to achieve? How many transfers has Globus supported for us? Which sites are we sharing the most data with, and how is that changing over time? How is my site using Globus to move data internally, and what kind of performance do we see for those transfers? What percentage of data transfers at my institution used Globus, and how did the overall data transfer performance compare to the Globus users?
Globus Connect Server Deep Dive - GlobusWorld 2024Globus
We explore the Globus Connect Server (GCS) architecture and experiment with advanced configuration options and use cases. This content is targeted at system administrators who are familiar with GCS and currently operate—or are planning to operate—broader deployments at their institution.
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
Games are powerful teaching tools, fostering hands-on engagement and fun. But they require careful consideration to succeed. Join me to explore factors in running and selecting games, ensuring they serve as effective teaching tools. Learn to maintain focus on learning objectives while playing, and how to measure the ROI of gaming in education. Discover strategies for pitching gaming to leadership. This session offers insights, tips, and examples for coaches, team leads, and enterprise leaders seeking to teach from simple to complex concepts.
In software engineering, the right architecture is essential for robust, scalable platforms. Wix has undergone a pivotal shift from event sourcing to a CRUD-based model for its microservices. This talk will chart the course of this pivotal journey.
Event sourcing, which records state changes as immutable events, provided robust auditing and "time travel" debugging for Wix Stores' microservices. Despite its benefits, the complexity it introduced in state management slowed development. Wix responded by adopting a simpler, unified CRUD model. This talk will explore the challenges of event sourcing and the advantages of Wix's new "CRUD on steroids" approach, which streamlines API integration and domain event management while preserving data integrity and system resilience.
Participants will gain valuable insights into Wix's strategies for ensuring atomicity in database updates and event production, as well as caching, materialization, and performance optimization techniques within a distributed system.
Join us to discover how Wix has mastered the art of balancing simplicity and extensibility, and learn how the re-adoption of the modest CRUD has turbocharged their development velocity, resilience, and scalability in a high-growth environment.
top nidhi software solution freedownloadvrstrong314
This presentation emphasizes the importance of data security and legal compliance for Nidhi companies in India. It highlights how online Nidhi software solutions, like Vector Nidhi Software, offer advanced features tailored to these needs. Key aspects include encryption, access controls, and audit trails to ensure data security. The software complies with regulatory guidelines from the MCA and RBI and adheres to Nidhi Rules, 2014. With customizable, user-friendly interfaces and real-time features, these Nidhi software solutions enhance efficiency, support growth, and provide exceptional member services. The presentation concludes with contact information for further inquiries.
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
Keep tabs on your field staff effortlessly with Informap Technology Centre LLC. Real-time tracking, task assignment, and smart features for efficient management. Request a live demo today!
For more details, visit us : https://informapuae.com/field-staff-tracking/
Advanced Flow Concepts Every Developer Should KnowPeter Caitens
Tim Combridge from Sensible Giraffe and Salesforce Ben presents some important tips that all developers should know when dealing with Flows in Salesforce.
Listen to the keynote address and hear about the latest developments from Rachana Ananthakrishnan and Ian Foster who review the updates to the Globus Platform and Service, and the relevance of Globus to the scientific community as an automation platform to accelerate scientific discovery.
2. 0A pre-dependency injection
Base example
Advantages
• easily enable testability
• clean and concise code
• testing client and service in isolation
• client no need to know how to build the dependency object graph
3. 0A pre-dependency injection
Encapsulate creation
1 public class Emailer {
2
3 private SpellChecker spellChecker;
4
5 public Emailer() {
6 this.spellChecker = new SpellChecker();
7 }
8
9 public void send(String text) {
10 //some implementation
11 }
12 }
How to test?
• Impossible: MockSpellChecker cannot substitute the internal spellChecker.
Change implementation?
• Impossible: Emailer encapsulates the creation of its dependencies.
4. 0A pre-dependency injection
Construction by hand
1 public class Emailer {
2
3 private SpellChecker spellChecker;
4
5 public void send(String text) {
6 //some implementation
7 }
8
9 public void setSpellChecker(SpellChecker spellChecker) {
10 this.spellChecker = spellChecker;
11 }
12 }
Pros
• Setter method: different flavors of the service can be injected.
Cons
• Object construction knowledge: on the client of the service.
• Repeat wiring code
• What about: encapsulation principle and altering the object graph?
5. 0A pre-dependency injection
Construction by hand test
Pros
• Setter method: MockSpellChecker can be easily injected.
• Check if dependency has been correctly used.
Cons
• Repeat wiring code
1 @Test
2 public void testEmailerCheckSpelling() throws Exception {
3
4 MockSpellChecker mockSpellChecker = new MockSpellChecker();
5
6 Emailer emailer = new Emailer();
7
8 emailer.setSpellChecker(mockSpellChecker);
9 emailer.send("Hello World");
10
11 assert mock.isSpellCheckingDone();
12 }
6. 0A pre-dependency injection
Factory pattern
Pros
• Level of abstraction: Emailer client code is separated from the Emailer creation.
• No internal knowledge: client code only use a specific factory to obtain a dependency.
• Code clean and concise even with richer and more complex object graph.
Cons
• Extreme growth: factory classes tend to grow becoming really big and uncontrolled.
1 public class EmailerFactory {
2
3 public Emailer newFrenchEmailer() {
4 return new Emailer(new FrenchSpellChecker());
5 }
6
7 public Emailer newJapaneseEmailer() {
8 return new Emailer(new JapaneseSpellChecker());
9 }
10 }
11
12 //somewhere in the Client code
13 Emailer emailer = new EmailerFactory().newFrenchEmailer();
7. 0A pre-dependency injection
Factory pattern test
Pros
• Level of abstraction: Emailer client code is separated from the Emailer creation.
• No internal knowledge: client code only use a specific factory to obtain a dependency.
• Code clean and concise even with richer and more complex object graph.
Cons
• Extreme growth and maintenance: factory classes tend to grow becoming really big and uncontrolled.
1 public class EmailerFactory {
2
3 public Emailer newFrenchEmailer() {
4 return new Emailer(new FrenchSpellChecker());
5 }
6
7 public Emailer newJapaneseEmailer() {
8 return new Emailer(new JapaneseSpellChecker());
9 }
10 }
11
12 //somewhere in the Client code
13 Emailer emailer = new EmailerFactory().newFrenchEmailer();
8. 0A pre-dependency injection
Factory pattern test
1 public class EmailClient {
2 private Emailer emailer = new EmailerFactory.newEnglishEmailer();
3
4 public void run() {
5 emailer.send("Hello World");
6 }
7 }
8
9 @Test
10 public void testEmailClient() {
11 MockEmailer mock = new MockEmailer();
12 EmailerFactory.set(mock);
13
14 new EmailClient.run();
15
16 assert mock.correctlySent();
17 }
How & Cons to test with factory
• Heavily modify factory class code to support testing for any client, state is shared thus
code cleanup required after each test.
• Create a factory mock or stub which can easily grow, it must accompany every variation
of every service.
9. 0B dependency injection
Hollywood Principle: don’t call us; we’ll call you!
Enable
• Unawareness: client not aware of the Emailer kind.
• Reversal of responsibilities: service not explicitly required.
Pros
• Easily enable testability via setter method or constructor injection (construction by hand).
• Client no needs to know its dependencies and how to build them (factory pattern).
• Dependencies are not required but provided (new).
1 public class Emailer {
2 public void send(String text) {
3 //some implementation
4 }
5 //some other methods
6 }
7
8 public class SimpleEmailClient {
9 private Emailer emailer;
10
11 public SimpleEmailClient(Emailer emailer) {
12 this.emailer = emailer;
13 }
14 public void sendEmail() {
15 emailer.send(readMessage());
16 }
17 }
10. 0B dependency injection
Hollywood Principle: don’t call us; we’ll call you!
embodies the
Hollywood Principle
Dependency Injector
• Control over construction, wiring and assembly dependency or object graph.
• Separates infrastructure code (wiring and construction) from application code (core
purpose of the service)
11. 0C dependency injection with Spring
Spring Framework
Spring
• Open source application framework and inversion of control container for Java platform.
• 1 October 2002, release 1.0.0, 7 July 2014, release 4.0.6, now 4.1.0 RC1
• active development and evolution to meet new programming requirements
• Developed by Pivotal, a spin-out and joint venture of EMC Corporation and VMware.
• Excellent documentation, clean and tested code, wide community and support.
Projects
• Spring Framework
• core support for dependency injection, transaction management
• Spring Data
• provide consistent approach to data access
• relational, non-relational, map-reduce and much more
• Spring XD
• simplify the development of big data applications
• address analytics, batch jobs and data export
• much more…
12. 0C dependency injection with Spring
Example: the client of the service
Client
• SimpleEmailClient decoupled from the EmailerService implementation.
• SimpleEmailClient unaware of which implementation will be provided at runtime,
programming against interfaces (OOP principle).
1 @Component
2 public class SimpleEmailClient {
3
4 final private EmailerService service;
5
6 @Autowired
7 public SimpleEmailClient(EmailerService service) {
8 this.service = service;
9 }
10
11 public void printMessage() {
12 System.out.println(this.service.getMessage());
13 }
14 }
13. 1 @Configuration
2 @ComponentScan
3 public class Application {
4
5 @Bean
6 MessageService mockEmailerService() {
7 return new EmailerService() {
8 public String getMessage() {
9 return "Hello World!";
10 }
11 };
12 }
13
14 public static void main(String[] args) {
15 ApplicationContext context =
16 new AnnotationConfigApplicationContext(Application.class);
17 SimpleEmailClient client = context.getBean(SimpleEmailClient.class);
18 client.printMessage();
19 }
20 }
0C dependency injection with Spring
Example: the service and the mock
Injected mock
implements the
interface
Injector wires client
with its dependency
14. 0C dependency injection with Spring
Another example with integration test
1 @Entity
2 @Table(name = "MOVIE")
3 public class Movie extends AbstractEntity {
4
5 @Column(name = "TITLE")
6 private String title;
7
8 protected Movie() {...}
9 }
Movie example
• Simple Movie class annotated JPA 2.0, Hibernate, store and retrieve.
• A service interface is given.
• Repository and service should be created and implemented to support basic CRUD operations.
Code on Github
• The code of the example is available on Github
1 public interface MovieService {
2
3 List<Movie> findAll();
4
5 Movie create(final Movie movie);
6
7 Movie delete(final Movie movie);
8
9 Movie update(final Movie movie);
10 }
15. 0C dependency injection with Spring
Integration test: another example
Movie repository and service
• No need to implement basic CRUD methods as findAll(), delete(), save() etc.
• Methods are resolved based on attribute names, just declare in the repository interface findById() to have
it automatically implemented at runtime where Id is the attribute.
• More complex methods have to be directly implemented.
• Clean and concise code, no need to implement explicit SQL query, reduce boiler-plate code.
1 @Repository
2 @Transactional
3 public class MovieServiceImpl implements MovieService {
4
5 @Autowired
6 private MovieRepository movieRepository;
7
8 @Override
9 public final List<Movie> findAll() {
10 return Lists.newArrayList(movieRepository.findAll());
11 }
12 ...
13 }
1 public interface MovieRepository extends CrudRepository<Movie, Long> {
2 }
16. 0C dependency injection with Spring
Integration test: another example
1 @ActiveProfiles("test")
2 public class MovieServiceImplTest extends AbstractServiceImplTest {
3
4
5 @Autowired
6 private MovieService movieService;
7
8 @DataSets(setUpDataSet = "/MovieServiceImplTest.xls")
9 @Test
10 public final void testFindAll() throws Exception {
11 List<Movie> results = movieService.findAll();
12
13 assertNotNull(results);
14 assertThat(results.size(), equalTo(3));
15 }
16 }
Injected
implementation based
on the interface
Build ApplicationContext
based on the active
profile
Insert into the data source tables
from xls file before the method
execution.
After method execution
automatic rollback.
17. 1 @RunWith(SpringJUnit4ClassRunner.class)
2 @ContextConfiguration(classes = {ServiceTestConfig.class})
3 @TestExecutionListeners({ServiceTestExecutionListener.class})
4 @ActiveProfiles("test")
5 public abstract class AbstractServiceImplTest extends
AbstractTransactionalJUnit4SpringContextTests {
6
7 @PersistenceContext
8 protected EntityManager em;
9 }
0C dependency injection with Spring
ApplicationContext
configuration with a
specific data source,
schema and data.
Based on a standard
JUnit Runner.
Standard javax.persistence,
hibernate jpa 2.0 api.
Listener to intercept
standard test execution
lifecycle.
Test
• Non invasive solution to build integration tests based on standard frameworks like
JUnit and Hibernate
• It works on top of standard frameworks providing clean and concise code for complex
test cases.
Integration test: another example
18. 1 @Configuration
2 @ImportResource("classpath:datasource-tx-jpa.xml")
3 @ComponentScan(basePackages = {"com.contrastofbeauty.movieapp.service"})
4 @Profile("test")
5 public class ServiceTestConfig {
6
7 @Bean
8 public DataSource dataSource() {
9 return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("classpath:schema.sql").build();
10 }
11
12 @Bean(name = "databaseTester")
13 public DataSourceDatabaseTester dataSourceDatabaseTester() {
14 DataSourceDatabaseTester databaseTester = new DataSourceDatabaseTester(dataSource());
15 return databaseTester;
16 }
17
18 @Bean(name = "xlsDataFileLoader")
19 public XlsDataFileLoader xlsDataFileLoader() {
20 return new XlsDataFileLoader();
21 }
22 }
0C dependency injection with Spring Reuse transaction and
JPA configuration
DbUnit classes to load xls files
and setup the data source
Data source
configuration
Integration test: another example
19. 0C dependency injection with Spring
Considerations
Spring Debate
• Spring is not standard.
• Just pointless, Spring promote the use of standard.
• Really important to have a standard, but if the solution of your problem is not standard you will
wait three or more years?
• Spring Social (JSR-357 rejected in 2012, really opened debate on future)
• Widespread container testing done with Arquillan, JBoss specific.
• Spring is not compatible.
• Free to use JPA, CDI annotations etc.
• Use all Java EE technologies and additional features provide by Spring.
• Spring works with all Java EE application servers and more like Jetty and Tomcat.
• Spring is a must, best choice
• Not always and Just pointless, what are your requirements?
• Spring is a meta-framework, highly scalable, highly configurable but complex.
• Spring configuration could be difficult to manage when the project grows.
• Use only Spring dependency injection? May be consider what already provided by the container.
20. 0D AngularJS
$scope, $controller, $http and test with mocks
Where to find the code
• Github for source code: angulajs-popcorn
• Plunker online live editing: application and testing
21. 0D AngularJS
Definition
MVC Design Pattern
• View is projection of the model through the HTML template.
• Controller is a Javascript constructor function used to augment the Angular scope.
• Scope an object referring to application model, used along with data model, template and controller to keep
models and views in sync.
Template Model View
(model/view data binding)
Root
Scope
movieController
Scope
movies: Array
<!DOCTYPE html>
<html lang="en" ng-app="movieApp">
<body ng-controller="movieController">
<ul>
<li ng-repeat="movie in movies">
{{movie.title}}
</li>
</ul>
</body>
</html>
Repetear
Scope
movie: Object
▪ Commando
▪ Raw Deal
▪ Predator
n-times
ng-controller
ng-app
n-times
22. 0D AngularJS dependency injection
Definition
Angular Injection
• $scope injected into controller, scope is the glue between application controller and the view.
• $http injected, an Angular service to facilitate the communication with the remote HTTP server.
• $httpBackend mock of the real $httpBackend, backend used by the service to delegate to XMLHttpRequest.
1 var movieApp = angular.module('movieApp', ['xeditable', 'ngMockE2E']);
2
3 movieApp.controller('MovieController', function($scope, $http) {
4
5 $scope.loadMovies = function() {
6 return $http.get("/movies").success(function(response){
7 $scope.movies = response;
8 });
9 };
10 });
11
12 // --------------- mock $http requests ----------------------
13 movieApp.run(function($httpBackend) {
14 $httpBackend.whenGET('/movies').respond([
15 {id: 1, title: "Commando", actors: "Arnold Schwarzenegger"},
16 {id: 2, title: "Raw Deal", actors: "Arnold Schwarzenegger"},
17 {id: 3, title: "Predator", actors: "Arnold Schwarzenegger"}
18 ])
19 });
23. 0D AngularJS dependency injection
Test controller using Jasmine BDD framework
1 describe('Movie Controller test suite', function() {
2
3 describe('MovieController', function() {
4
5 var $scope, $httpBackend, createController, $http;
6
7 beforeEach(module('movieApp'));
8
9 beforeEach(inject(function($controller, $rootScope, _$httpBackend_, _$http_) {
10 $scope = $rootScope.$new();
11 $httpBackend = _$httpBackend_;
12 $http = _$http_;
13
14 createController = function() {
15 return $controller('MovieController', {
16 $scope: $scope
17 });
18 };
19 }));
20
21 it("should GET all the movies", function() {
22 $httpBackend.expectGET('/movies').respond(200, [{}, {}, {}]);
23 createController();
24 $scope.loadMovies();
25 $httpBackend.flush();
26 expect($scope.movies.length).toBe(3);
27 });
28 });
Jasmine description suite
Setup test context injecting
Angular services
Jasmine test declaration
or spec
Obtain the controller and
invoke the function to test
Assert the result
24. 0D AngularJS
Considerations
Advantages
• clean separation of concerns
• template is pure HTML, no other languages
• injection and made for testing
• two-way data binding, change in the view is reflected in the model and viceversa
• directives, markers on the DOM element to attach specific behavior or transform the element (ng-repeat)
• powerful and scalable to support big projects
• really well documented, excellent support, big community, fast growing set of libraries
Disadvantages
• learning curve, takes time
• best practices needed to avoid bad programming patterns i.e. code can be written inside of templates
• complexity, some parts are a bit complex to understand