The document discusses testing rich domain models. It begins by explaining why testing domain models is important, as it allows finding errors faster through unit tests rather than slower integration tests. Testing domain models also improves code quality and makes the application more maintainable. The document then covers different approaches to testing services, entities, and value objects that make up a domain model. It discusses using mocks and test doubles to isolate objects for testing while also testing collaborations. Overall the document argues that testing at the domain model level has significant benefits and discusses best practices for writing effective tests of domain objects.
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Steve Pember
In this presentation we will present the general philosophy of Clean Architecture, Hexagonal Architecture, and Ports & Adapters: discussing why these approaches are useful and general guidelines for introducing them to your code. Chiefly, we will show how to implement these patterns within your Spring (Boot) Applications. Through a publicly available reference app, we will demonstrate what these concepts can look like within Spring and walkthrough a handful of scenarios: isolating core business logic, ease of testing, and adding a new feature or two.
Nowadays traditional layered monolithic architecture in Java world is not so popular as 5-10 years ago. I remember how we wrote tons of code for each layer repeating almost the same parts for every application. Add unit and integration testing to understand how much time and efforts has been spent on repeatable work. All cool ideas around DDD (domain driven design) and Hexagonal Architecture was just a nice theory because reality hasn’t allow us to implement it easily. Even Dependency Injection with Spring framework was completely focused on traditional layered approach, not even talking about JavaEE platform.
Today we have Spring Boot ecosystem covering most of our needs for integration with almost all possible technologies and microservices architectural trend, enabling completely new approach to build Java applications around domain model. It is so natural to build Java domain-oriented services and connect them with external world using ports and adapters, that Hexagonal Architecture is almost enabled by default. You just need to switch your way of thinking…
Breakthrough OLAP performance with Cassandra and SparkEvan Chan
Find out about breakthrough architectures for fast OLAP performance querying Cassandra data with Apache Spark, including a new open source project, FiloDB.
Domain Driven Design (DDD) is a topic that's been gaining a lot of popularity in both the Java and .NET camps recently. Entities, value types, repositories, bounded contexts and anti-corruption layers -- find out what all the buzz is about, and how establishing a domain model can help you combat complexity in your code.
Richard Dingwall is a .NET developer and blogger with a passion for architecture and maintainable code.
He is currently working at Provoke Solutions as lead developer on a six-month project introducing test-driven development (TDD) and domain-driven design (DDD) to a large ASP.NET ERP system.
An hour-long talk given at Wellington .NET user group, Sept 23 2009.
Anatomy of a Spring Boot App with Clean Architecture - Spring I/O 2023Steve Pember
In this presentation we will present the general philosophy of Clean Architecture, Hexagonal Architecture, and Ports & Adapters: discussing why these approaches are useful and general guidelines for introducing them to your code. Chiefly, we will show how to implement these patterns within your Spring (Boot) Applications. Through a publicly available reference app, we will demonstrate what these concepts can look like within Spring and walkthrough a handful of scenarios: isolating core business logic, ease of testing, and adding a new feature or two.
Nowadays traditional layered monolithic architecture in Java world is not so popular as 5-10 years ago. I remember how we wrote tons of code for each layer repeating almost the same parts for every application. Add unit and integration testing to understand how much time and efforts has been spent on repeatable work. All cool ideas around DDD (domain driven design) and Hexagonal Architecture was just a nice theory because reality hasn’t allow us to implement it easily. Even Dependency Injection with Spring framework was completely focused on traditional layered approach, not even talking about JavaEE platform.
Today we have Spring Boot ecosystem covering most of our needs for integration with almost all possible technologies and microservices architectural trend, enabling completely new approach to build Java applications around domain model. It is so natural to build Java domain-oriented services and connect them with external world using ports and adapters, that Hexagonal Architecture is almost enabled by default. You just need to switch your way of thinking…
Breakthrough OLAP performance with Cassandra and SparkEvan Chan
Find out about breakthrough architectures for fast OLAP performance querying Cassandra data with Apache Spark, including a new open source project, FiloDB.
Domain Driven Design (DDD) is a topic that's been gaining a lot of popularity in both the Java and .NET camps recently. Entities, value types, repositories, bounded contexts and anti-corruption layers -- find out what all the buzz is about, and how establishing a domain model can help you combat complexity in your code.
Richard Dingwall is a .NET developer and blogger with a passion for architecture and maintainable code.
He is currently working at Provoke Solutions as lead developer on a six-month project introducing test-driven development (TDD) and domain-driven design (DDD) to a large ASP.NET ERP system.
An hour-long talk given at Wellington .NET user group, Sept 23 2009.
Introduction to the Spring Framework:
Generar description
IoC container
Dependency Injection
Beans scope and lifecycle
Autowiring
XML and annotation based configuration
Additional features
The domain model is an abstraction of the problem domain that your system supports. It contains the objects and operations that are crucial to your system and its users. Therefore the design of the domain model deserves the utmost care and attention. In this session you will be introduced to Domain-Driven Design and you will learn how to put Domain-Driven Design (DDD) into practice. We will explore how to apply DDD on tactical level to design a rich domain model that encapsulates behaviour, protects its invariants and can be tested in isolation from its runtime environment
Distributed Transactions is a key concept for Micro Services based Apps and Saga Design Pattern helps out over here. However, developers struggle to shift their mindset from CRUD based design to Event Sourcing / CQRS concept. To solve this problem we are introducing the concept of Event Storming and Event Storming Process map.
Retour opérationnel sur la clean architectureRomainKuzniak
Retour opérationnel sur la Clean Architecture. OpenClassrooms utilise la Clean Architecture depuis près de 5 ans d'utilisation, il est temps de faire un bilan opérationnel.
In this tutorial on Kotlin Jetpack, we will learn why Jetpack compose, What is Kotlin Jetpack compose, and How does compose works?. We will also learn about Composable function, Layouts, and material design. At last, we will have a look at the List and animations.
What is Kotlin Jetpack compose?
Why Jetpack compose?
How does the compose work?
Composable function
Layouts
Material design
List and animations
NgRx is a framework for building reactive applications in Angular. NgRx provides state management, isolation of side effects, entity collection management, router bindings, code generation, and developer tools that enhance developers experience when building many different types of applications
This slide covers redux design pattern, ngrx store and effects and how they communicate and debugging with ngrx store dev-tools.
This talk introduces Spring's REST stack - Spring MVC, Spring HATEOAS, Spring Data REST, Spring Security OAuth and Spring Social - while refining an API to move higher up the Richardson maturity model
When developing applications we have a hard time managing application state, and that is okay because managing application state is hard. We will try to make it easier using Redux.
Redux is predictable state management container for JavaScript applications that helps us manage our state while also making our state mutations predictable.
Through the presentation and code, I will show you how I solved my state problem with Redux in React application.
An introduction to a possible implementation of CQRS/ES architecture for a Ruby on Rails app. It starts from Domain Model to arrive to a sample app that implements the Event Sourcing pattern. This presentation was part of Wroclove_rb 2014 conference in Wraclow (PL)
Introduction to the Spring Framework:
Generar description
IoC container
Dependency Injection
Beans scope and lifecycle
Autowiring
XML and annotation based configuration
Additional features
The domain model is an abstraction of the problem domain that your system supports. It contains the objects and operations that are crucial to your system and its users. Therefore the design of the domain model deserves the utmost care and attention. In this session you will be introduced to Domain-Driven Design and you will learn how to put Domain-Driven Design (DDD) into practice. We will explore how to apply DDD on tactical level to design a rich domain model that encapsulates behaviour, protects its invariants and can be tested in isolation from its runtime environment
Distributed Transactions is a key concept for Micro Services based Apps and Saga Design Pattern helps out over here. However, developers struggle to shift their mindset from CRUD based design to Event Sourcing / CQRS concept. To solve this problem we are introducing the concept of Event Storming and Event Storming Process map.
Retour opérationnel sur la clean architectureRomainKuzniak
Retour opérationnel sur la Clean Architecture. OpenClassrooms utilise la Clean Architecture depuis près de 5 ans d'utilisation, il est temps de faire un bilan opérationnel.
In this tutorial on Kotlin Jetpack, we will learn why Jetpack compose, What is Kotlin Jetpack compose, and How does compose works?. We will also learn about Composable function, Layouts, and material design. At last, we will have a look at the List and animations.
What is Kotlin Jetpack compose?
Why Jetpack compose?
How does the compose work?
Composable function
Layouts
Material design
List and animations
NgRx is a framework for building reactive applications in Angular. NgRx provides state management, isolation of side effects, entity collection management, router bindings, code generation, and developer tools that enhance developers experience when building many different types of applications
This slide covers redux design pattern, ngrx store and effects and how they communicate and debugging with ngrx store dev-tools.
This talk introduces Spring's REST stack - Spring MVC, Spring HATEOAS, Spring Data REST, Spring Security OAuth and Spring Social - while refining an API to move higher up the Richardson maturity model
When developing applications we have a hard time managing application state, and that is okay because managing application state is hard. We will try to make it easier using Redux.
Redux is predictable state management container for JavaScript applications that helps us manage our state while also making our state mutations predictable.
Through the presentation and code, I will show you how I solved my state problem with Redux in React application.
An introduction to a possible implementation of CQRS/ES architecture for a Ruby on Rails app. It starts from Domain Model to arrive to a sample app that implements the Event Sourcing pattern. This presentation was part of Wroclove_rb 2014 conference in Wraclow (PL)
The Long Sad History of MicroServices (Greg Young Technology Stream)IT Arena
Lviv IT Arena is a conference specially designed for programmers, designers, developers, top managers, inverstors, entrepreneurs and startuppers. Annually it takes place at the beginning of October in Lviv at Arena Lviv stadium. In 2016 the conference gathered more than 1800 participants and over 100 speakers from companies like Microsoft, Philips, Twitter, UBER and IBM. More details about the conference at itarena.lviv.ua.
Video link: https://vimeo.com/131377935
Talk for Monitorama 2015. The history (or quasi history) of microservices and how to begin to approach monitoring from the POV of a smaller startup/company.
Intelligent Business Process Management Suites (iBPMS) - The Next-Generation ...Kai Wähner
I had a talk at ECSA 2014 in Vienna: The Next-Generation BPM for a Big Data World: Intelligent Business Process Management Suites (iBPMS), sometimes also abbreviated iBPM. I want to share the slides with you. The slides include an example how to implement iBPMS easily with the TIBCO middleware stack: TIBCO AMX BPM + BusinessWorks + StreamBase + Tibbr.
In building large scale web applications MVC seems like a good solution in the initial design phase. However after having built a few large apps that have multiple entry points (web, cli, api etc) you start to find that MVC breaks down. Start using Domain Driven Design.
Domain-driven design (DDD) is an approach to software development for complex needs by connecting the implementation to an evolving model.[1] The premise of domain-driven design is the following:
Placing the project's primary focus on the core domain and domain logic.
Basing complex designs on a model of the domain.
Initiating a creative collaboration between technical and domain experts to iteratively refine a conceptual model that addresses particular domain problems.
Have more questions?
Twitter: @wajrcs
Web: http://waqaralamgir.tk
TEDx Manchester: AI & The Future of WorkVolker Hirsch
TEDx Manchester talk on artificial intelligence (AI) and how the ascent of AI and robotics impacts our future work environments.
The video of the talk is now also available here: https://youtu.be/dRw4d2Si8LA
One day Chris Richardson, in need of a rich UI and deeply frustrated with Javascript and CSS, sat on his couch and downloaded FlexBuilder. This is what he found out.
CommunityOneEast 09 - Dynamic Languages: the next big thing for the JVM or an...Chris Richardson
There is a good reason why dynamic languages such as Groovy and Ruby are getting a lot of attention. They are powerful, expressive languages that enable developers to easily write concise programs. However, not all of their benefits derive from being dynamic. Many important benefits are simply due to modern language design such as the support for closures. Moreover, dynamic languages have some inherent drawbacks. The extremely limited compile-time checking requires developers to write significantly more tests and severely limits how much help an IDE can provide to a developer.
In this session, which is aimed at Java developers and architects, you will learn
• What it means for a language to be dynamic
• Which Groovy features we liked the most
• The frustrating side of Groovy development
• How Groovy compares to Scala, which is a modern statically typed language that provides many of benefits of Groovy
Presentation on Continuous Deployment with Deployit that Vincent Partington gave at the BCS CMSG conference in London on June the 7th 2011.
http://www.bcs-cmsg.org.uk/conference2011/conference.html
This talk was given at SOA Symposium in Amsterdam in 2008. It is a perspective on Enterprise Mashup architectures can be constructed by using data services, RIA, REST, empowering the client platforms.
A Data Scientist And A Log File Walk Into A Bar...Paco Nathan
Presented at Splunk .conf 2012 in Las Vegas. Includes an overview of the Cascading app based on City of Palo Alto open data. PS: email me if you need a different format than Keynote: @pacoid or pnathan AT concurrentinc DOT com
A common microservice architecture anti-pattern is more the merrier. It occurs when an organization team builds an excessively fine-grained architecture, e.g. one service-per-developer. In this talk, you will learn about the criteria that you should consider when deciding service granularity. I'll discuss the downsides of a fine-grained microservice architecture. You will learn how sometimes the solution to a design problem is simply a JAR file.
YOW London - Considering Migrating a Monolith to Microservices? A Dark Energy...Chris Richardson
This is a talk I gave at YOW! London 2022.
Let's imagine that you are responsible for an aging monolithic application that's critical to your business. Sadly, getting changes into production is a painful ordeal that regularly causes outages. And to make matters worse, the application's technology stack is growing increasingly obsolete. Neither the business nor the developers are happy. You need to modernize your application and have read about the benefits of microservices. But is the microservice architecture a good choice for your application?
In this presentation, I describe the dark energy and dark matter forces (a.k.a. concerns) that you must consider when deciding between the monolithic and microservice architectural styles. You will learn about how well each architectural style resolves each of these forces. I describe how to evaluate the relative importance of each of these forces to your application. You will learn how to use the results of this evaluation to decide whether to migrate to the microservice architecture.
Dark Energy, Dark Matter and the Microservices Patterns?!Chris Richardson
Dark matter and dark energy are mysterious concepts from astrophysics that are used to explain observations of distant stars and galaxies. The Microservices pattern language - a collection of patterns that solve architecture, design, development, and operational problems — enables software developers to use the microservice architecture effectively. But how could there possibly be a connection between microservices and these esoteric concepts from astrophysics?
In this presentation, I describe how dark energy and dark matter are excellent metaphors for the competing forces (a.k.a. concerns) that must be resolved by the microservices pattern language. You will learn that dark energy, which is an anti-gravity, is a metaphor for the repulsive forces that encourage decomposition into services. I describe how dark matter, which is an invisible matter that has a gravitational effect, is a metaphor for the attractive forces that resist decomposition and encourage the use of a monolithic architecture. You will learn how to use the dark energy and dark matter forces as guide when designing services and operations.
Dark energy, dark matter and microservice architecture collaboration patternsChris Richardson
Dark energy and dark matter are useful metaphors for the repulsive forces, which encourage decomposition into services, and the attractive forces, which resist decomposition. You must balance these conflicting forces when defining a microservice architecture including when designing system operations (a.k.a. requests) that span services.
In this talk, I describe the dark energy and dark matter forces. You will learn how to design system operations that span services using microservice architecture collaboration patterns: Saga, Command-side replica, API composition, and CQRS patterns. I describe how each of these patterns resolve the dark energy and dark matter forces differently.
It sounds dull but good architecture documentation is essential. Especially when you are actively trying to improve your architecture.
For example, I spend a lot time helping clients modernize their software architecture. More often than I like, I’m presented with a vague and lifeless collection of boxes and lines. As a result, it’s sometimes difficult to discuss the architecture in a meaningful and productive way. In this presentation, I’ll describe techniques for creating minimal yet effective documentation for your application’s microservice architecture. In particular, you will learn how documenting scenarios can bring your architecture to life.
Using patterns and pattern languages to make better architectural decisions Chris Richardson
This is a presentation that gave at the O'Reilly Software Architecture Superstream: Software Architecture Patterns.
The talk's focus is the microservices pattern language.
However, it also shows how thinking with the pattern mindset - context/problem/forces/solution/consequences - leads to better technically decisions.
The microservices architecture offers tremendous benefits, but it’s not a silver bullet. It also has some significant drawbacks. The microservices pattern language—a collection of patterns that solve architecture, design, development, and operational problems—enables software developers to apply the microservices architecture effectively. I provide an overview of the microservices architecture and examines the motivations for the pattern language, then takes you through the key patterns in the pattern language.
Rapid, reliable, frequent and sustainable software development requires an architecture that is loosely coupled and modular.
Teams need to be able complete their work with minimal coordination and communication with other teams.
They also need to be able keep the software’s technology stack up to date.
However, the microservice architecture isn’t always the only way to satisfy these requirements.
Yet, neither is the monolithic architecture.
In this talk, I describe loose coupling and modularity and why they are is essential.
You will learn about three architectural patterns: traditional monolith, modular monolith and microservices.
I describe the benefits, drawbacks and issues of each pattern and how well it supports rapid, reliable, frequent and sustainable development.
You will learn some heuristics for selecting the appropriate pattern for your application.
Events to the rescue: solving distributed data problems in a microservice arc...Chris Richardson
To deliver a large complex application rapidly, frequently and reliably, you often must use the microservice architecture.
The microservice architecture is an architectural style that structures the application as a collection of loosely coupled services.
One challenge with using microservices is that in order to be loosely coupled each service has its own private database.
As a result, implementing transactions and queries that span services is no longer straightforward.
In this presentation, you will learn how event-driven microservices address this challenge.
I describe how to use sagas, which is an asynchronous messaging-based pattern, to implement transactions that span services.
You will learn how to implement queries that span services using the CQRS pattern, which maintain easily queryable replicas using events.
A pattern language for microservices - June 2021 Chris Richardson
The microservice architecture is growing in popularity. It is an architectural style that structures an application as a set of loosely coupled services that are organized around business capabilities. Its goal is to enable the continuous delivery of large, complex applications. However, the microservice architecture is not a silver bullet and it has some significant drawbacks.
The goal of the microservices pattern language is to enable software developers to apply the microservice architecture effectively. It is a collection of patterns that solve architecture, design, development and operational problems. In this talk, I’ll provide an overview of the microservice architecture and describe the motivations for the pattern language. You will learn about the key patterns in the pattern language.
QConPlus 2021: Minimizing Design Time Coupling in a Microservice ArchitectureChris Richardson
Delivering large, complex software rapidly, frequently and reliably requires a loosely coupled organization. DevOps teams should rarely need to communicate and coordinate in order to get work done. Conway's law states that an organization and the architecture that it develops mirror one another. Hence, a loosely coupled organization requires a loosely coupled architecture.
In this presentation, you will learn about design-time coupling in a microservice architecture and why it's essential to minimize it. I describe how to design service APIs to reduce coupling. You will learn how to minimize design-time coupling by applying a version of the DRY principle. I describe how key microservices patterns potentially result in tight design time coupling and how to avoid it.
Mucon 2021 - Dark energy, dark matter: imperfect metaphors for designing micr...Chris Richardson
In order to explain certain astronomical observations, physicists created the mysterious concepts of dark energy and dark matter.
Dark energy is a repulsive force.
It’s an anti-gravity that is forcing matter apart and accelerating the expansion of the universe.
Dark matter has the opposite attraction effect.
Although it’s invisible, dark matter has a gravitational effect on stars and galaxies.
In this presentation, you will learn how these metaphors apply to the microservice architecture.
I describe how there are multiple repulsive forces that drive the decomposition of your application into services.
You will learn, however, that there are also multiple attractive forces that resist decomposition and bind software elements together.
I describe how as an architect you must find a way to balance these opposing forces.
Skillsmatter CloudNative eXchange 2020
The microservice architecture is a key part of cloud native.
An essential principle of the microservice architecture is loose coupling.
If you ignore this principle and develop tightly coupled services the result will mostly likely be yet another "microservices failure story”.
Your application will be brittle and have all of disadvantages of both the monolithic and microservice architectures.
In this talk you will learn about the different kinds of coupling and how to design loosely coupled microservices.
I describe how to minimize design time and increase the productivity of your DevOps teams.
You will learn how how to reduce runtime coupling and improve availability.
I describe how to improve availability by minimizing the coupling caused by your infrastructure.
DDD SoCal: Decompose your monolith: Ten principles for refactoring a monolith...Chris Richardson
This is a talk I gave at DDD SoCal.
1. Make the most of your monolith
2. Adopt microservices for the right reasons
3. It’s not just architecture
4. Get the support of the business
5. Migrate incrementally
6. Know your starting point
7. Begin with the end in mind
8. Migrate high-value modules first
9. Success is improved velocity and reliability
10. If it hurts, don’t do it
Decompose your monolith: Six principles for refactoring a monolith to microse...Chris Richardson
This was a talk I gave at the CTO virtual summit on July 28th. It describes 6 principles for refactoring to a microservice architecture.
1. Make the most of your monolith
2. Adopt microservices for the right reasons
3. Migrate incrementally
4. Begin with the end in mind
5. Migrate high-value modules first
6. Success is improved velocity and reliability
The microservice architecture is becoming increasingly important. But what is it exactly? Why should you care about microservices? And, what do you need to do to ensure that your organization uses the microservice architecture successfully? In this talk, I’ll answer these and other questions. You will learn about the motivations for the microservice architecture and why simply adopting microservices is insufficient. I describe essential characteristics of microservices, You will learn how a successful microservice architecture consists of loosely coupled services with stable APIs that communicate asynchronously.
"Impact of front-end architecture on development cost", Viktor TurskyiFwdays
I have heard many times that architecture is not important for the front-end. Also, many times I have seen how developers implement features on the front-end just following the standard rules for a framework and think that this is enough to successfully launch the project, and then the project fails. How to prevent this and what approach to choose? I have launched dozens of complex projects and during the talk we will analyze which approaches have worked for me and which have not.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
Let's dive deeper into the world of ODC! Ricardo Alves (OutSystems) will join us to tell all about the new Data Fabric. After that, Sezen de Bruijn (OutSystems) will get into the details on how to best design a sturdy architecture within ODC.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Key Trends Shaping the Future of Infrastructure.pdf
Testing Rich Domain Models
1. Testing Rich Domain Models
Chris i h d
Ch i Richardson
Author of POJOs in Action
Chris Richardson C
Ch i Ri h d Consulting, I
lti Inc
http://www.chrisrichardson.net
3/1/2009 1
Copyright (c) 2007 Chris Richardson. All rights reserved.
2. Overview
Testing a rich
g
domain model:
Why? How?
3/1/2009 2
Copyright (c) 2007 Chris Richardson. All rights reserved.
3. About Chris
Grew up in England
Live in Oakland, CA
Over twenty years of software
development experience
Building object-oriented
g j
software since 1986
Using Java since 1996
Using J2EE since 1999
Author of POJOs in Action
Speaker at JavaOne, JavaPolis,
SpringOne, NFJS, JUGs, ….
Chair of the eBIG Java SIG in
Oakland (www.ebig.org)
Run a consulting and training
company that helps organizations
build better software faster
3/1/2009 3
Copyright (c) 2007 Chris Richardson. All rights reserved.
4. Agenda
g
Introduction
Testing services
Testing entities and value objects
g j
Taming test fixture logic
Simplifying verification code
Writing more meaningful tests
3/1/2009 4
Copyright (c) 2007 Chris Richardson. All rights reserved.
5. Using the Domain Model Pattern
g
Traditional enterprise Java applications:
Business l i i f t service
Bi logic in fat i
Services manipulate dumb Java beans
Doesn t
Doesn't handle complexity
Domain model pattern:
Business logic spread amongst a collection
of classes
fl
Many classes are true objects having both
state (fields) and behavior (
( ) (methods) the
)
state
Many classes correspond to real world
concepts: Order Customer, …
Order, Customer
3/1/2009 5
Copyright (c) 2007 Chris Richardson. All rights reserved.
6. Procedural versus OO
Presentation Tier
Presentation Tier
Business Tier
Business Tier
Transaction
Scripts
Facade
(Session
Beans)
Domain Model
Data
Objects
Obj
Data Access Tier
Data Access Tier
3/1/2009 6
Copyright (c) 2007 Chris Richardson. All rights reserved.
7. An example domain model
p
Web Tier
Behavior
Business Tier
MoneyTransferService
BankingTransaction transfer(fromId, toId, amount)
from
Account
Banking Account
BankingTransaction
Transaction Repository
Repository
balance
to
amount findAccount(id)
addTransaction(…) debit(amount)
date
credit(amount)
Explicit
<<interface>>
OverdraftPolicy
Representation
State +
of key
Behavior Limited
concepts
p
NoOverdraft Overdraft
Policy
y
limit
3/1/2009 7
Copyright (c) 2007 Chris Richardson. All rights reserved.
8. Why test?
y
Write new code more easily
Automates what we are doing already
- Right!?
Run fast unit tests instead of slower
web application
pp
Use TDD to incrementally solve a
problem
Tests are a safety net
y
Confidently change existing code
Easier to refactor code to prevent
decay
The application has longer, healthier
life
Fewer bugs that impact customers
g p
AND development
3/1/2009 8
Copyright (c) 2007 Chris Richardson. All rights reserved.
9. Why test a domain model?
y
Benefits of pushing tests down
p g
the hierarchy:
Easier and cheaper
Faster
Better error localization
You change a complex interest
calculation:
How do you want to test it:
Through a changing GUI?
With simple unit tests
When do you want to find out
whether it works?
15 minutes later after running
web tests?
10 seconds later after running
hundreds of unit tests?
Determining why a test fails?
Because of a problem with the
database or UI?
Because the algorithm was
wrong?
3/1/2009 9
Copyright (c) 2007 Chris Richardson. All rights reserved.
10. Domain models make testing easier
g
More modular:
Smaller classes/methods that are easier
to test
Business l i i
i logic implemented b
l d by
immutable value objects
Functions are easier to test that code
h d
with side-effects
Back to basics - POJOs with no
dependencies on infrastructure
Quickly test in isolation
3/1/2009 10
Copyright (c) 2007 Chris Richardson. All rights reserved.
11. Domain models make testing more
difficult…
Domain models are often used when the
business logic is complex
Objects are structurally more complex
Not relational – i.e. not flat, coarse-grained
Finer grained objects, i.e. many classes map to the
same table)
Richer relationships between objects
Deeper object graphs
Object behavior is more complex
Behavior determined by collaborators + internal
state (reflects previous method invocations)
Classes are often modal: imposes ordering on
method invocations
3/1/2009 11
Copyright (c) 2007 Chris Richardson. All rights reserved.
12. …Domain models make testing
more difficult
Richer collaborations
Service does more than invoke getters and
setters on domain objects
Domain objects invoke methods on one
another
Encapsulation
p
Domain Objects != JavaBeans
Perhaps getters but preferably not setters
Initializing objects is more complex
Verifying object state might be more difficult
3/1/2009 12
Copyright (c) 2007 Chris Richardson. All rights reserved.
13. Excellent testing book
g
Test smells and how to fix them
Obscure test
Fragile test
Test code duplication
…
Comprehensive pattern
C h i tt
language:
Four phase test
Minimal fixture
Test utility method
Test helper
Humble Object
…
3/1/2009 13
Copyright (c) 2007 Chris Richardson. All rights reserved.
14. Agenda
g
Introduction
Testing services
Testing entities and value objects
g j
Taming test fixture logic
Simplifying verification code
Writing more meaningful tests
3/1/2009 14
Copyright (c) 2007 Chris Richardson. All rights reserved.
15. What's a Service?
A role that some domain public interface MoneyTransferService {
model classes play BankingTransaction transfer(String fromAccountId,
String toAccountId, double amount)
Implements logic that throws MoneyTransferException;
cannot be put in a single }
entity
Not
N t persistent
it t public class MoneyTransferServiceImpl implements MoneyTransferService
{
Consists of an interface
and an implementation private final AccountRepository accountRepository;
class private final BankingTransactionRepository
bankingTransactionRepository;
Service method usually:
Invoked (indirectly) by public MoneyTransferServiceImpl(AccountRepository accountRepository,
BankingTransactionRepository bankingTransactionRepository) {
presentation tier this.accountRepository = accountRepository;
Invokes one or more this.bankingTransactionRepository = bankingTransactionRepository;
repositories }
Invokes one or more entities public B ki T
bli BankingTransaction t
ti transfer(String f
f (St i fromAccountId,
A tId
Well-designed services String toAccountId, double amount) {
…
are thin fromAccount.debit(amount);
toAccount.credit(amount);
Improves code quality …
Makes them easier to test }
}
3/1/2009 15
Copyright (c) 2007 Chris Richardson. All rights reserved.
16. How to test a service?
p
public class MoneyTransferServiceImpl implements MoneyTransferService {
y p p y
private final AccountRepository accountRepository;
private final BankingTransactionRepository bankingTransactionRepository;
public MoneyTransferServiceImpl(AccountRepository accountRepository,
BankingTransactionRepository b ki
ki i i bankingTransactionRepository) {
i i )
this.accountRepository = accountRepository;
this.bankingTransactionRepository = bankingTransactionRepository;
}
public BankingTransaction transfer(String fromAccountId
fromAccountId,
String toAccountId, double amount) throws MoneyTransferException {
Account fromAccount = accountRepository.findAccount(fromAccountId);
Account toAccount = accountRepository.findAccount(toAccountId);
fromAccount.debit(amount);
toAccount.credit(amount);
TransferTransaction txn = new TransferTransaction(fromAccount,
toAccount, amount, new Date());
bankingTransactionRepository.addTransaction(txn);
return txn;
Database access
}
…
3/1/2009 16
Copyright (c) 2007 Chris Richardson. All rights reserved.
17. Writing service integration tests
Fixture logic: public class SpringMoneyTransferServiceTests extends
AbstractDependencyInjectionSpringContextTests {
…
Creates service @Override
protected String[] getConfigLocations() {
return new String[] { quot;classpath:/appCtx/*.xmlquot; };
Initializes database }
Exercise phase:
E i h public void setService(MoneyTransferService service) {
bli id tS i (M T fS i i)
this.service = service;
}
Calls service @Override
Verification:
protected void onSetUp() throws Exception {
super.onSetUp();
fromAccount = AccountMother
Check state of .makeAccountWithNoOverdraft(FROM_ACCOUNT_INITIAL_BALANCE);
toAccount = AccountMother
database and .makeAccountWithNoOverdraft(TO_ACCOUNT_INITIAL_BALANCE);
fromAccountId = fromAccount.getAccountId();
return values toAccountId = toAccount.getAccountId();
repository.addAccount(fromAccount);
repository.addAccount(toAccount);
repository addAccount(toAccount);
Teardown: }
public void testTransfer() {
clean up service.transfer(fromAccountId, toAccountId, 5);
assertBalance(FROM_ACCOUNT_INITIAL_BALANCE - 5, fromAccountId);
(somehow) assertBalance(TO_ACCOUNT_INITIAL_BALANCE + 5, toAccountId);
}
3/1/2009 17
Copyright (c) 2007 Chris Richardson. All rights reserved.
18. The trouble with integration tests
g
Require lots of setup
Setting up the database
gp
Initializing the database
…
10x-100x slower than in-memory tests:
y
Use an in-memory database, e.g. HSQLDB
Don’t commit transactions
Database = persistence ⇒ test interference
p
Execute each test in a transaction that is rolled back
⇒ can interfere with session flushing/object loading
Recreate the database schema ⇒ works well with
HSQLDB
Somehow write tests that only see data that they
insert – can be tricky
We still need integration tests but we can often
g
do better…
3/1/2009 18
Copyright (c) 2007 Chris Richardson. All rights reserved.
19. Faster testing with mock objects
g j
A mock object
simulates the real
object:
Returns values or
throws exceptions
th ti
Verifies that the
expected methods are
called
Using mocks:
Simplifies tests
Speeds up tests
Enables an obje t to
object
be tested in isolation
Enables top-down
development
3/1/2009 19
Copyright (c) 2007 Chris Richardson. All rights reserved.
20. Creating mocks
g
Write your own mocks
Simple for interfaces but it becomes
tedious.
How t mock concrete classes?
H to k tl ?
Use a mock object framework
jMOCK, EasyMock
Create and configure mock object
Specify expected method and arguments
Define method behavior: return value or
throw exception
th ti
3/1/2009 20
Copyright (c) 2007 Chris Richardson. All rights reserved.
21. Mock objects example: p
j p part 1
import org.jmock…;
public class MoneyTransferServiceTests extends MockObjectTestCase {
protected void setUp() {
super.setUp();
accountRepository = mock(AccountRepository class);
mock(AccountRepository.class);
bankingTransactionRepository =
mock(BankingTransactionRepository.class);
service = new MoneyTransferServiceImpl(accountRepository,
bankingTransactionRepository);
Create
service with
fromAccount = AccountMother.makeAccount(100);
mock
toAccount = AccountMother.makeAccount(200);
fromAccountId = fromAccount getAccountId();
fromAccount.getAccountId();
repositories
ii
toAccountId = toAccount.getAccountId();
}
3/1/2009 21
Copyright (c) 2007 Chris Richardson. All rights reserved.
22. Mock objects example: p
j p part 2
p
public class MoneyTransferServiceTests extends TestCase {
y
public void testTransfer_normal() throws Exception {
checking(new Expectations() {
{
one(accountRepository).findAccount(fromAccountId);
will(returnValue(fromAccount));
ill( l (f ))
one(accountRepository).findAccount(toAccountId);
will(returnValue(toAccount));
one(bankingTransactionRepository).addTransaction(
with(is(BankingTransaction.class)));
}
});
BankingTransaction result = service
.transfer(fromAccountId, toAccountId, 30);
assertNotNull(result);
MoneyUtil.assertMoneyEquals(70.0, fromAccount.getBalance());
MoneyUtil.assertMoneyEquals(230.0, toAccount.getBalance());
}
3/1/2009 22
Copyright (c) 2007 Chris Richardson. All rights reserved.
23. Downsides of mocks
Testing the collaboration of objects =
white box testing
Tests can be brittle
Change design without changing what it
does ⇒ failing tests
Discourages ddevelopers f
l from writing
tests
Fortunately,
Fortunately many collaborations are
stable
e.g.
e g between services and repositories
3/1/2009 23
Copyright (c) 2007 Chris Richardson. All rights reserved.
24. Mock selectively!
y
Collaborators that slow tests down or
introduce undesirable coupling:
Repositories
Remote Services
Collaborators that require elaborate
initialization,
Stateful entities and value objects
Collaborators that don't exist (yet)
Entities when developing top down
top-down
Applications where message ordering is
important
3/1/2009 24
Copyright (c) 2007 Chris Richardson. All rights reserved.
25. Agenda
g
Introduction
Testing services
Testing entities and value objects
g j
Taming test fixture logic
Simplifying verification code
Writing more meaningful tests
3/1/2009 25
Copyright (c) 2007 Chris Richardson. All rights reserved.
26. What's an Entity?
y
Objects with a public class Account {
distinct identity private int id;
Typically correspond
private double balance;
to real world
private OverdraftPolicy overdraftPolicy;
private String accountId;
concepts private CalendarDate dateOpened;
Almost always Account() {
persistent
}
public void debit(double amount) throws MoneyTransferException {
Encapsulate state and assert amount > 0;
double originalBalance = balance;
behavior double newBalance = balance - amount;
overdraftPolicy.beforeDebitCheck(this, originalBalance, newBalance);
balance = newBalance;
Often modal ⇒ overdraftPolicy.afterDebitAction(this, originalBalance, newBalance);
}
testing is more public void credit(double amount) {
difficult assert amount > 0;
balance += amount;
}
3/1/2009 26
Copyright (c) 2007 Chris Richardson. All rights reserved.
27. What's a Value Object?
j
public class Account
Objects that are defined
private CalendarDate dateOpened;
public class CalendarDate {
by the values of their …
p ate ate
private Date date; }
attributes CalendarDate() {
Two instances with
}
identical values can be public CalendarDate(Date date) {
this.date = date;
used interchangeably }
Two flavors public Date getDate() {
return date;
Persistent – parts of }
entities public double getYearsOpen() {
Calendar then = Calendar.getInstance();
Transient – intermediate then.setTime(date);
values Calendar now = Calendar.getInstance();
Ideally immutable int yearsOpened = now.get(Calendar.YEAR) –
then.get(Calendar.YEAR);
Often missing from int monthsOpened = now.get(Calendar.MONTH) -
then.get(Calendar.MONTH);
procedural code
d ld if (monthsOpened < 0) {
( th O d
yearsOpened--;
Have encapsulated state monthsOpened += 12;
}
and behavior return yearsOpened + (monthsOpened/12.0);
}
}
3/1/2009 27
Copyright (c) 2007 Chris Richardson. All rights reserved.
28. Aggregates
gg g
A cluster of related
entities and values
Behaves as a unit
Has a root
Has b
H a boundaryd
Objects outside the
aggregate can only
reference the root
Deleting the root
removes everything
Tests often create
and test aggregates
rather than
individual objects
3/1/2009 28
Copyright (c) 2007 Chris Richardson. All rights reserved.
29. Tests for entities and value objects
j
Fixture logic
Create object under test (OUT) (often an
aggregate)
Create collaborators (also aggregates)
Execution
E ec tion
Invoke method on OUT
Verification
Return value
State of OUT
State of collaborators
Cleanup
Usually do nothing – just use the g
y gj garbage
g
collector
3/1/2009 29
Copyright (c) 2007 Chris Richardson. All rights reserved.
30. Testing a POJO domain object
g j
p
public class AccountTests extends TestCase {
p
public class Account {
private Account account;
private String accountId;
private double balance; public void setUp() {
private OverdraftPolicy account = new Account(quot;ABCquot;, 10.0, new
overdraftPolicy;
d ftP li NoOverdraftAllowed());
d f ll d())
}
public double getBalance() {
public void testInitialBalance() {
return balance;
MoneyUtil.assertMoneyEquals(10.0,
} account.getBalance());
account getBalance());
}
public void debit(double amount)
public void testDebit() {
{…}
account.debit(6);
MoneyUtil.assertMoneyEquals(4.0,
public void credit(double
account.getBalance());
amount) { … } }
…
Relatively easy to write tests }
that run blindingly fast
3/1/2009 30
Copyright (c) 2007 Chris Richardson. All rights reserved.
31. Mocking collaborators
g
Used less often - collaborators are
usually fast to create
But it can sometimes simplify tests
Account and OverdraftPolicy
Separate tests Account and
OverdraftPolicies ⇒ Fewer, simpler tests
But perhaps causes a feeling that you
are not testing completely
t t ti ltl
Useful when creating a collaborator
requires writing a l t of code
i iti lot f d
3/1/2009 31
Copyright (c) 2007 Chris Richardson. All rights reserved.
32. Agenda
g
Introduction
Testing services
Testing entities and value objects
g j
Taming test fixture logic
Simplifying verification code
Writing more meaningful tests
3/1/2009 32
Copyright (c) 2007 Chris Richardson. All rights reserved.
33. What's a fixture
Fixture = everything that needs to
be in place to test an object
Object we want to test
Its collaborators
Fixture is created by test fixture
logic:
Code in the test methods themselves
Junit 3.x setUp()
JUnit 4/TestNG @Before* annotations
3/1/2009 33
Copyright (c) 2007 Chris Richardson. All rights reserved.
34. The challenge of test fixtures
g
Creating objects isn't always easy
Individual objects have lots of parameters
Objects are often belong to aggregates
Test fixtures often create multiple
T t fi t ft t lti l
objects
MoneyTransferServiceTests needs two
accounts
Multiple tests need the same set of
objects
AccountTests, MoneyTransferServiceTests need
similar A
i il Account objects
t bj t
3/1/2009 34
Copyright (c) 2007 Chris Richardson. All rights reserved.
35. Object g p
j graphs can be complicated
p
We need all
of these
objects to
test a
Project!
3/1/2009 35
Copyright (c) 2007 Chris Richardson. All rights reserved.
36. Constructing individual objects can
be tricky
y
Best way to construct an object is to
use a constructor:
Supports objects without setters
Supports immutable objects
Forces you to support everything that's
required
Limitations of constructors:
Lots of constructor arguments ⇒ code is
difficult
diffi l to read
d
Optional arguments ⇒ multiple
constructors
3/1/2009 36
Copyright (c) 2007 Chris Richardson. All rights reserved.
37. The alternative to constructors
Project project = new Project(initialStatus);
project.setName(quot;Test Project #1quot;);
project.setDescription(quot;descriptionquot;);
project.setRequirementsContactName(quot;Rick Jonesquot;);
project.setRequirementsContactEmail(quot;jones@nowhere.comquot;);
project.setType(ProjectType.EXTERNAL_DB);
project.setArtifacts(new ArtifactType[] {
ArtifactType.ARCHITECTURE,
ArtifactType.DEPLOYMENT, ArtifactType.MAINTENANCE });
project.setInitiatedBy(user);
•Handles optional parameters
•Is more readable
•But lots of noise: 'project set'
project.set
3/1/2009 37
Copyright (c) 2007 Chris Richardson. All rights reserved.
38. Constructing objects fluently
g j y
Project project = new Project(initialStatus)
.name(quot;Test Project #1quot;)
.description(quot;Excellent projectquot;)
.initiatedBy(user)
.requirementsContactName(quot;Rick Jonesquot;)
.requirementsContactEmail(quot;jones@nowhere.comquot;)
.type(ProjectType.EXTERNAL_DB)
.artifact(ArtifactType.ARCHITECTURE)
.artifact(ArtifactType.DEPLOYMENT)
.artifact(ArtifactType.MAINTENANCE);
• Chained method calls
3/1/2009 38
Copyright (c) 2007 Chris Richardson. All rights reserved.
39. Pros and cons of this approach
pp
Benefits:
Less noise
Meaning of each value is clear
Drawbacks:
Breaks encapsulation – objects must
have mutators/setters
Doesn't work with immutable objects
3/1/2009 39
Copyright (c) 2007 Chris Richardson. All rights reserved.
40. Fluently creating immutable objects
y g j
See
http://developers.sun.com/learning/javaoneonl
http://developers sun com/learning/javaoneonl
ine/2007/pdf/TS-2689.pdf
Project project = new Project.ProjectBuilder(initialStatus)
.name(quot;Test Project #1quot;)
(quot; j
.description(quot;descriptionquot;)
.initiatedBy(user)
.requirementsContactName(quot;Rick Jonesquot;)
.requirementsContactEmail(quot;jones@nowhere.comquot;)
i C il(quot;j @ h quot;)
.type(ProjectType.EXTERNAL_DB)
.artifact(ArtifactType.ARCHITECTURE)
.artifact(ArtifactType.DEPLOYMENT)
.artifact(ArtifactType.MAINTENANCE)
tif t(A tif tT MAINTENANCE)
.make();
• Initialize the mutable builder
• make() instantiates the domain
object i
obje t via a constructor
on t to
• Allows entity to be immutable
3/1/2009 40
Copyright (c) 2007 Chris Richardson. All rights reserved.
41. Nested Entity Builder example
y p
class Project {
public class ProjectBuilder {
private String name;
…
public ProjectBuilder(Status initialStatus) {
this.status = status;
}
ProjectBuilder name(String name) {
this.name = name;
return this;
}
public Project make() {
// Verify that we have everything
return new Project(this);
}
}
• Pass builder as the sole
public Project(ProjectBuilder builder) {
constructor argument
this.name = builder.name;
this.initiatedBy = builder.initiatedBy;
}
3/1/2009 41
Copyright (c) 2007 Chris Richardson. All rights reserved.
42. Centralizing object creation with
Object Mothers
j
Fluent interfaces can help
but public class ProjectMother {
Fixture logic can still be public static Project
complex makeProjectInProposalState (
Status initialStatus, User user) {
Same object created in …
multiple t t ⇒ d li ti
lti l tests duplication }
Eliminate duplication: public static Project
Centralize object creation in makeProjectInRequirementsState(
Status initialStatus, User user) {
a test utility class called an
Object Mother …
Defines factory methods for }
creating fully formed
aggregate }
Different methods for
different aggregate states
See: http://www xpuniverse com/2001/pdfs/Testing03 pdf
http://www.xpuniverse.com/2001/pdfs/Testing03.pdf
3/1/2009 42
Copyright (c) 2007 Chris Richardson. All rights reserved.
43. Creating multiple connected
aggregates
gg g
Each Object Mother
method creates a
single aggregate
But
B t some tests need
tt d
to create multiple
aggregates with
shared sub-
h d b
aggregates itDepartment = DepartmentMother.makeItDepartment();
Must avoid itProjectManager =
duplicating that code
UserMother.makeProjectManager(itDepartment);
itBusinessAnalyst =
UserMother.makeBusinessAnalyst(itDepartment);
in multiple fixtures projectInCompleteState =
ProjectMother.makeProjectInCompleteState(…);
projectInRequirementsState =
ProjectMother.makeProjectInRequirementsState(…);
P j tM th k P j tI R i t St t ( )
…
3/1/2009 43
Copyright (c) 2007 Chris Richardson. All rights reserved.
44. Use stateful object mothers
j
Test instantiates object mother
Object mother's constructor
Creates aggregates (by calling their
Object Mothers)
Stores them in (public) fields
Test gets the data it needs from the
object mother
3/1/2009 44
Copyright (c) 2007 Chris Richardson. All rights reserved.
45. Example of a stateful mother
public class ProjectTests extends TestCase {
private Project project;
private User projectManager;
private User businessAnalyst;
public class PTrackWorld {
protected void setUp() throws Exception {
private final Department itDepartment; PTrackWorld world = new PTrackWorld();
private fi l User itP j tM
i t final U itProjectManager; projectManager = world.getItProjectManager();
private final Project projectInCompleteState; businessAnalyst = world.getItBusinessAnalyst();
project = world.getProjectInProposalState();
}
…
public PTrackWorld() {
itDepartment = DepartmentMother.makeItDepartment()'
itProjectManager = UserMother.makeProjectManager(itDepartment);
stateMachine = DefaultStateMachineFactory.makeStateMachine(quot;defaultquot;);
initialStatus = stateMachine.getInitialStatus();
projectInCompleteState = ProjectMother.makeProjectInCompleteState(initialStatus,
itProjectManager, getAllITDepartmentEmployees());
…
}
}
3/1/2009 45
Copyright (c) 2007 Chris Richardson. All rights reserved.
46. Object Mother design
j g
Choices
Same data each time vs. random data
Referenced aggregates as parameters vs. create
those aggregates too
Tip: use descriptive names
Bad: makeProject1(), makeProject2(), ...
Better: makeProjectIn<State>(), …
Tip: use Object Mothers from day 1
But don’t create obscure tests
Hiding details in mothers can make tests difficult to
understand
ShoppingCartMother.makeWithInstockPartBackorderedPartandDiscontinuedPart() ?!?
Need to find the balance between too much and too
little
3/1/2009 46
Copyright (c) 2007 Chris Richardson. All rights reserved.
47. Agenda
g
Introduction
Testing services
Testing entities and value objects
g j
Taming test fixture logic
Simplifying verification code
Writing more meaningful tests
3/1/2009 47
Copyright (c) 2007 Chris Richardson. All rights reserved.
48. Writing readable verification logic
Verification phase verifies that expected
outcome has been obtained
State verification makes assertions about:
Returned value
State of object under test
State of collaborators
Test frameworks provide the basic assert
methods but we must:
Ensure readability
Avoid code duplication
3/1/2009 48
Copyright (c) 2007 Chris Richardson. All rights reserved.
49. Using Custom Assertions
Verifying the state of object
multiple assert…() calls = obscure code
In multiple tests = code duplication
Verification code calls a Test Utility
Method that makes assertions
Has an Intention Revealing Name
Benefits:
Makes the code more readable
Eliminates duplication
p
3/1/2009 49
Copyright (c) 2007 Chris Richardson. All rights reserved.
50. Example – before and after
protected void setUp() throws Exception {
PTrackWorld world = new PTrackWorld();
projectManager = world.getItProjectManager();
project = world.getProjectInProposalState();
protected void setUp() throws Exception {
startTime = new Date();
…
expectedOperation0 =
state0 = world.getInitialState();
new Operation(null, projectManager,
state1 = state0.getApprovalStatus();
state0, state1,
state2 = state1.getApprovalStatus();
g pp ();
quot;Excellentquot;);
quot; ll quot;)
}
}
public void testChangeStatus() throws InterruptedException {
public void testChangeStatus()
boolean result = project.changeStatus(true,
{
projectManager, quot;Excellentquot;);
boolean result = project.changeStatus(true,
Date endTime = new Date();
projectManager, quot;E
j tM quot;Excellentquot;);
ll tquot;)
Date endTime = new Date();
assertTrue(result);
assertEquals(state1, project.getStatus());
assertTrue(result);
assertEquals(1, project.getHistory().size());
assertEquals(state1, project.getStatus());
Operation operation = project.getHistory().get(0);
assertHistoryContains(project,
assertHistoryContains(project
assertEquals(quot;Excellentquot;, operation.getComments());
l (quot; ll quot; i C ())
startTime, endTime,
assertEquals(projectManager, operation.getUser());
expectedOperation0);
assertEquals(state0, operation.getFromStatus());
}
assertEquals(state1, operation.getToStatus());
assertFalse(operation.getTimestamp().before(startTime));
assertFalse(operation.getTimestamp().after(endTime));
}
3/1/2009 50
Copyright (c) 2007 Chris Richardson. All rights reserved.
51. Example - After
private void assertHistoryContains(Project project, Date startTime,
Date endTime,
Operation... expectedOperations) {
int i = 0;
List<Operation> history = project.getHistory();
assertEquals(expectedOperations.length, history.size());
for (Operation expectedOperation : expectedOperations) {
Operation operation = history.get(i++);
assertOperationEqual(expectedOperation, startTime, endTime,
assertOperationEqual(expectedOperation startTime endTime
operation);
startTime = operation.getTimestamp();
}
}
private void assertOperationEqual(Operation expectedOperation, Date startTime,
Date endTime, Operation operation) {
assertEquals(expectedOperation.getComments(), operation.getComments());
assertEquals(expectedOperation.getUser(), operation.getUser());
assertEquals(expectedOperation.getFromStatus(), operation.getFromStatus());
assertEquals(expectedOperation getFromStatus() operation getFromStatus());
assertEquals(expectedOperation.getToStatus(), operation.getToStatus());
assertFalse(operation.getTimestamp().before(startTime));
assertFalse(operation.getTimestamp().after(endTime));
}
3/1/2009 51
Copyright (c) 2007 Chris Richardson. All rights reserved.
52. Literate assertions with Hamcrest
Hamcrest is an open-source framework
http://code.google.com/p/hamcrest/
Readable quot;literatequot; assertions
Rich set of composable matchers
Literate error messages
Used by Jmock expectations
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
org hamcrest Matchers is;
import static org.hamcrest.Matchers.isOneOf;
assertThat(project.getStatus(), is(state1));
assertThat(project.getStatus(), isOneOf(state1, state2));
assertThat(project.getStatus(), allOf(is(state), not(is(state2))));
tTh t( jt tSt t () llOf(i ( t t ) t(i ( t t 2))))
3/1/2009 52
Copyright (c) 2007 Chris Richardson. All rights reserved.
53. Hamcrest custom matchers
public class ProjectMatchers {
p
public static Matcher<Date> withinInclusivePeriod(final Date startTime,
( ,
final Date endTime) {
return new TypeSafeMatcher<Date>() {
public boolean matchesSafely(Date date) {
return !date.before(startTime) && !date.after(endTime);
}
public void describeTo(Description description) {
description.appendText(String.format(quot;expected to be between <%s> and <%s>quot;,
startTime, endTime));
}
import static org.jia.ptrack.domain.ProjectMatchers.withinInclusivePeriod;
p gj p j ;
};
} public void testChangeStatus() {
assertThat(operation.getTimestamp(),
is(withinInclusivePeriod(startTime, endTime)));
}
java.lang.AssertionError:
Expected: is expected to be between <Wed Nov 14 19:39:23 PST 2007> and
<Wed Nov 14 19:39:23 PST 2007>
got: <Wed Dec 31 16:00:00 PST 1969>
at
org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:21)
g ( j )
3/1/2009 53
Copyright (c) 2007 Chris Richardson. All rights reserved.
54. Agenda
g
Introduction
Testing services
Testing entities and value objects
g j
Taming test fixture logic
Simplifying verification code
Writing more meaningful tests
3/1/2009 54
Copyright (c) 2007 Chris Richardson. All rights reserved.
55. TDD says begin with a test but…
Daddy, where do
tests come from?
3/1/2009 55
Copyright (c) 2007 Chris Richardson. All rights reserved.
56. Best to derive tests from
requirements
q
As a customer of the bank
I want to transfer money between two bank accounts
So that I don't have to write a check
class AccountTransferServiceTests … {
public void testTransfer_ok() {
Account savingsAccount =
AccountMother.makeAccountWithNoOverdraft(150);
Account checkingAccount =
Given that my savings account balance is $150 AccountMother.makeAccountWithNoOverdraft(10);
Given that my checking account balance is $10 String savingsAccountId = savingsAccount.getAccountId();
When I transfer $50 from my savings account String checkingAccountId = checkingAccount.getAccountId();
to my checking account repository.addAccount(savingsAccount);
Then my savings account balance is $100 repository.addAccount(checkingAccount);
p y ( g );
Then my checking account balance is $60
service.transfer(savingsAccountId, checkingAccountId, 50);
assertBalance(100, savingsAccountId);
assertBalance(60, checkingAccountId);
}
Given that my savings account balance is $150
Given that my checking account balance is $10
public void testTransfer_overdraftAttempted() {
Given that my bank does not allow me
….
to have an overdraft
}
When I transfer $200 from my savings account
to my checking account
y g
Then my savings account balance is unchanged
Then my checking account balance is unchanged
3/1/2009 56
Copyright (c) 2007 Chris Richardson. All rights reserved.
57. Testing at multiple levels
g p
Where in the hierarchy to write a test?
Web tier
Service integration test
Mock service test
Entity/Value object test
Sometimes at every level
Few high-level tests, e g verify that the UI
tests e.g.
handles errors
Many lower-level, more detailed tests, e.g. tests
for each error scenario
Sometimes only lower-level tests
E.g. verifying that email is sent after
transferring money ⇒ mock object service test
fi k bj i
3/1/2009 57
Copyright (c) 2007 Chris Richardson. All rights reserved.
58. We sometimes invent requirements
q
User requirements focus on the external
behavior:
Behavior of boundary classes, i.e. UI +
services
Key domain model classes, e.g. account
But those classes often have
collaborators:
E.g. Account has CalendarDate
When designing those classes:
Informally specify the behavior of those
classes
Write capture that behavior in tests
3/1/2009 58
Copyright (c) 2007 Chris Richardson. All rights reserved.
59. More formal testing
g
1000+ pages of
rigorous testing
techniques
3/1/2009 59
Copyright (c) 2007 Chris Richardson. All rights reserved.
60. Deriving tests from a state machine
model
• State machine is a useful way
to model some classes (and
(
r
UIs)
• N+ test strategy
• Turn state machine into a
p q
A B C
tree containing all edges
• Test cases = paths to all
leaves
s
•Test = sequence of events
public testPQR() {
}
public testPS() {
}
3/1/2009 60
Copyright (c) 2007 Chris Richardson. All rights reserved.
61. Deriving tests from boolean
expressions
p
Class invariant/function/conditional: (x >= 1 & y < 10)
Variable Condition Test #1 #2 #3 #4
x X >= 1
> On 1
Off 0
Typical 10 10
Y Y < 10 On 10
Off 9
Typical 2 2
Result True False False True
1x1 selection criteria
3/1/2009 61
Copyright (c) 2007 Chris Richardson. All rights reserved.
62. Derive tests from code
Write tests to improve
code coverageg
Identifies
behavior/edge cases
that you forgot to test
Characterization tests:
Capture current
behavior
Useful for refactoring
(sometimes)
But they can be brittle
Tip: Use a code coverage
Code might not be tool: Cobertura (f
t l Cb t (free),
)
correct! Clover (cheap), …
3/1/2009 62
Copyright (c) 2007 Chris Richardson. All rights reserved.
63. Use code metrics to identify what
to test
Cyclomatic
complexity
Bugs lurk here
Simplify if you can
Large methods
L th d
Bugs lurk in here also
Simplify if you can
Crap4J
(www.crap4j.org)
Computes code
quality by combining
code coverage and
complexity
3/1/2009 63
Copyright (c) 2007 Chris Richardson. All rights reserved.
64. Summary
y
Testing is essential
Use mock objects to accelerate tests
Aggressively refactor tests to keep
gg y p
them simple
Use Object Mothers to avoid
j
duplication of test fixture logic
Simplify assertions
Derive tests from requirements
3/1/2009 64
Copyright (c) 2007 Chris Richardson. All rights reserved.
65. For more information
Buy my book ☺
Go to manning.com
Send email:
chris@chrisrichardson.net
Visit my website:
http://www.chrisrichardson.
net
Talk to me about
consulting and training
3/1/2009 65
Copyright (c) 2007 Chris Richardson. All rights reserved.