1
1
Spring Test Framework
Kostiantyn Baranov
Senior Software Engineer
2
3
0. Introduction
4
Whatta hell it’s starting from 0
4
5
What to expect
● Mems & Gifs
● A little bit of theory
6
● “Brilliant” Humor
● Demo
What to expect
7
● Spring 4 + Spring Boot 1.5
● Docker
● Gradle
● H2
● PostgreSQL
● Scaffolding
Technologies stack & Tools
8
Java 8, not Java 10
9
IDEA vs Eclipse
9
10
● ~5 years at GL
● All the way from Trainee to Senior
● Trainer & Mentor at GL Training
Center
● ZiftSolutions project employee
● Working with Microservice arch
based on Spring and Spring Boot,
Gradle & Docker with AWS
About myself
11
Why i’m doing this
12
● Scaffolding
● REST API
● Testing Concepts
● Spring Core/Spring Boot
● Spring Test
● Demo
● What next pay attention to
Agenda
13
1. Scaffolding
14
Programming
15
Scaffolding
● Saves time
● Show best practise
16
Scaffolding & Code Generation
17
Yeoman Generator
18
Yeoman - Java & Spring
● More than 100 generators
19
● Generating project structure
● Generating getter/setters/constructors
● Apply refactoring
● Shortcuts
● File Templates
Intellij IDEA
20
Spring Roo & Spring Initializer
21
Swagger
22
JHipster
JHipster is a development platform to generate, develop and
deploy Spring Boot + Angular/React Web applications and Spring
microservices.
23
As Summary
24
2. REST API
25
REST (Representational State Transfer) is an architectural
style for designing network applications, driven by a set of
constraints and inspired from the architecture of the Web.
REST
26
REST is entirely separate from the HTTP protocol, but in practice we're
primarily building APIs on top of HTTP. So the goal is to leverage the
full semantics of the protocol and use it as an application protocol
(rather than just transport).
HTTP & REST
27
EJB 3.0
EJB 3.0 & SOAP
EJB 2.0
SOAP
28
This fundamental constraint enforces a separation of concerns and
enables independent evolution of the Client and the Server.
Constraint 1 - Client-Server
29
The communication between Client and Server must be stateless
between requests.
First: each request from a client should contain all the necessary
information for the service to complete the request.
Second: all session state data should then be returned to the client at the
end of each request.
Constraint 2 - Stateless
30
All responses from the Server should be explicitly labeled as cacheable or
non-cacheable. Requests should pass through a Cache Component - which
can partially or fully eliminate some interactions with the Server.
Constraint 3 - Cache
31
The Service and all Clients must share a single uniform technical interface.
In order for that interface to be reusable by a wide range of Clients, it
needs to provide generic, high-level capabilities that are abstract enough
to accommodate a broad range of interactions.
Constraint 4 - Interface / Uniform Contract
32
The interaction between a Service and a Client should be fully
transparent and consistent, regardless if the Client is
communicating directly with the ultimate receiver of a message
or not.
This kind of information hiding greatly simplifies the distributed
architecture of the system and allows individual architectural
layers to be deployed and evolved independently of specific
services and consumers.
Constraint 5 - Layered System
33
● The Resource is the key abstraction of information in
REST. Any information that can be named / identified
via a unique, global id (the URI) - is a Resource.
● Any given Resource can have multiple Representations
- these capture the current state of the Resource in a
specific format. At the lowest level, the Representation
is "a sequence of bytes, plus representation
metadata to describe these bytes".
Resource & Representation
34
Richardson Maturity Model
35
3. Testing Concepts, i guess
36
1. It costs a lot (i.e. expensive, takes time)
2. It’s boring
3. It’s working anyway
4. It’s not my problem, i’m going on vacation for a
month
Why you shouldn’t write tests
37
38
● Better than frequent fire in prod
● Profit for the team
● It’s YOUR problem
Why you !!should!! write tests
39
Maintainability
40
● Understanding of requirements
● Refactoring insurance
● Documenting features
● Improving API
● Reducing errors
Advantages to dev
41
Test Pyramid
42
● Fast
● Isolated
● Repeatable
● Self-verifying
● Timely
F.I.R.S.T. aka SOLID for tests
43
Keep bugs out of your code
44
Unit testing isn’t good enough
45
The goal of integration testing, is to test whether many
separately developed modules work together as expected
Goal of Integration Testing
46
Let’s look closer to notion of integration testing
● narrow integration tests
● broad integration tests
47
● exercise only that portion of the code in service that
talks to a separate service
● uses test mocks/stubs of those services, either in
process or remote call
● thus consist of many narrowly scoped tests, often no
larger in scope than a unit test (and usually run with the
same test framework that's used for unit tests)
Narrow integration tests
48
● require live versions of all services, requiring
substantial test environment and network access
● exercise code paths through all services, not just
code responsible for interactions
Broad integration tests
49
As summary
50
As Summary
Если ваша программа сделана из говна и палок, то нужно
как минимум три типа тестов: на гавно, на палки и
интеграционные.
51
4. Spring
52
Spring Ecosystem
53
Spring framework offers a comprehensive list of features:
● Spring MVC web application and RESTful web
service framework
● Aspect-Oriented Programming including Spring’s
declarative transaction management
● Dependency Injection
● Inversion of Control
and much more.
Spring Features
54
● new MyObject() -> IoC container
● Manage object lifecycle
What is Inversion of Control
55
What is Dependency Injection
<bean name="customerRepository" class="org.repository.CustomerRepositoryHibernate"/>
<bean name="customerService" class="org.service.CustomerServiceImpl">
<property name="customerRepository" ref="customerRepository"></property>
</bean>
Container that finds a bean, pushes it wherever it is required,
and resolves the dependency. We don't look it up ourselves
to find them. We are just declaring where we need them.
56
Confidential
about managing dependencies by selectively
inverting key dependencies to prevent fragility of the
code & increase usability and stability
© Uncle Bob
OOP is
57
● @Component
● @Repository
● @Service
● @Controller
● @Configuration
Spring Stereotypes
58
Spring beans naming convention problem
59
Spring MVC
60
Dispatcher Servlet
61
● WebApplicationContext - web application context which extends
ApplicationContext with a contract for accessing the ServletContext.
● Applications usually should not be concerned about those
implementation details: the root web application context is simply a
centralized place to define shared beans. The root web application context
described in the previous section is managed by a listener of class
org.springframework.web.context.ContextLoaderListener
● Version 3 of the Servlet API has made configuration through the
web.xml file completely optional.
Spring Web Contexts - Root Web Context
62
● Spring MVC applications have at least one Dispatcher Servlet
configured
● Each DispatcherServlet has an associated application context.
Spring Web Contexts - Dispatcher Servlet Context
63
● Supports RESTful URLs
● Annotation based configuration (i.e. developers may
reduce the metadata file or less of configuration)
● Flexible in supporting different View types like JSP,
Thymeleaf, Velocity, XML, PDF, Tiles etc
Advantages of Spring MVC Framework
64
● Powerful repository and custom object-mapping
abstractions
● Dynamic query derivation from repository method names
● Implementation domain base classes providing basic
properties
● Support for transparent auditing (created, last changed)
● Possibility to integrate custom repository code
● Easy Spring integration via JavaConfig and custom XML
namespaces
● Advanced integration with Spring MVC controllers
● Experimental support for cross-store persistence
Spring Data Feature
65
Spring Data Repositories
66
……
and many more
Spring Data Query Creation
67
● @RequestBody & @ResponseBody
● @RestContoller & @Controller
● @ResponseStatus
● @RequestMapping & @RequestParam
● @PathVariable
…
> You can customize binding from request to object via
HandlerMethodArgumentResolver implementation
Spring Rest Annotations
68
● @ControllerAdvice
● @ExceptionHandler - only applies to the controller in
which it is defined
● RuntimeExceptions are preferable
Error Handling
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException {
//
}
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
//
}
69
● Create stand-alone Spring applications
● Embed Tomcat, Jetty or Undertow directly (no need
to deploy WAR files)
● Easy Dependency Management & Automatically
configure Spring and 3rd party libraries whenever
possible
● Provide production-ready features such as metrics,
health checks and externalized configuration
● Auto Configuration
Spring Boot features
70
Spring Boot AutoConfiguration
71
Example: A -> B -> C -> D 1.4 and A -> E -> D 1.0
This example shows that project A depends on B and E. B and E have their own
dependencies which encounter different versions of the D artifact. Artifact D 1.0 will
be used in the build of A project because the path through E is shorter.
Maven BOM
72
● @SpringBootApplication
● @EnableAutoConfiguration
● @Conditional and other @ConditionalOn...
Spring Boot Annotations
73
Spring Boot in nutshell
74
5. Spring Test
75
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-
testing.html
Let’s go to documentation?
76
● SpringRunner for jUnit 4
● @MockMVC & @WebMvcTest
● @RestClientTest & TestRestTemplate
● @ContextConfiguration & @WebAppConfiguration
● @DataJpaTest & @SpringBootTest
● @TestConfiguration
● @PropertySource
● @ActiveProfiles
● @ContextHierarchy
● @DirtiesContext
● @TestExecutionListeners
● JsonPath
● …..
Spring Test
77
● @ContextConfiguration
● @WebAppConfiguration
● @TestConfiguration
● @ActiveProfiles
● @ContextHierarchy
● @PropertySource
● @DirtiesContext
Spring Test Configuration
78
What feeling If you mess up test configuration
79
● SpringApplicationInitializer
● TestExecutionListener
Spring Test Customization
80
● TestContainers
● Docker jUnit 4 Rule
Docker
81
6.DEMO
82
I suspect
83
DEMO
84
As sum up
85
7. What next pay attention to
86
Worth to mention frameworks to dig in
87
Worth to mention frameworks to dig in
88
89
Q/A
90
91
92
Thank you

Spring Test Framework

  • 1.
  • 2.
    Spring Test Framework KostiantynBaranov Senior Software Engineer 2
  • 3.
  • 4.
    4 Whatta hell it’sstarting from 0 4
  • 5.
    5 What to expect ●Mems & Gifs ● A little bit of theory
  • 6.
  • 7.
    7 ● Spring 4+ Spring Boot 1.5 ● Docker ● Gradle ● H2 ● PostgreSQL ● Scaffolding Technologies stack & Tools
  • 8.
  • 9.
  • 10.
    10 ● ~5 yearsat GL ● All the way from Trainee to Senior ● Trainer & Mentor at GL Training Center ● ZiftSolutions project employee ● Working with Microservice arch based on Spring and Spring Boot, Gradle & Docker with AWS About myself
  • 11.
  • 12.
    12 ● Scaffolding ● RESTAPI ● Testing Concepts ● Spring Core/Spring Boot ● Spring Test ● Demo ● What next pay attention to Agenda
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
    18 Yeoman - Java& Spring ● More than 100 generators
  • 19.
    19 ● Generating projectstructure ● Generating getter/setters/constructors ● Apply refactoring ● Shortcuts ● File Templates Intellij IDEA
  • 20.
    20 Spring Roo &Spring Initializer
  • 21.
  • 22.
    22 JHipster JHipster is adevelopment platform to generate, develop and deploy Spring Boot + Angular/React Web applications and Spring microservices.
  • 23.
  • 24.
  • 25.
    25 REST (Representational StateTransfer) is an architectural style for designing network applications, driven by a set of constraints and inspired from the architecture of the Web. REST
  • 26.
    26 REST is entirelyseparate from the HTTP protocol, but in practice we're primarily building APIs on top of HTTP. So the goal is to leverage the full semantics of the protocol and use it as an application protocol (rather than just transport). HTTP & REST
  • 27.
    27 EJB 3.0 EJB 3.0& SOAP EJB 2.0 SOAP
  • 28.
    28 This fundamental constraintenforces a separation of concerns and enables independent evolution of the Client and the Server. Constraint 1 - Client-Server
  • 29.
    29 The communication betweenClient and Server must be stateless between requests. First: each request from a client should contain all the necessary information for the service to complete the request. Second: all session state data should then be returned to the client at the end of each request. Constraint 2 - Stateless
  • 30.
    30 All responses fromthe Server should be explicitly labeled as cacheable or non-cacheable. Requests should pass through a Cache Component - which can partially or fully eliminate some interactions with the Server. Constraint 3 - Cache
  • 31.
    31 The Service andall Clients must share a single uniform technical interface. In order for that interface to be reusable by a wide range of Clients, it needs to provide generic, high-level capabilities that are abstract enough to accommodate a broad range of interactions. Constraint 4 - Interface / Uniform Contract
  • 32.
    32 The interaction betweena Service and a Client should be fully transparent and consistent, regardless if the Client is communicating directly with the ultimate receiver of a message or not. This kind of information hiding greatly simplifies the distributed architecture of the system and allows individual architectural layers to be deployed and evolved independently of specific services and consumers. Constraint 5 - Layered System
  • 33.
    33 ● The Resourceis the key abstraction of information in REST. Any information that can be named / identified via a unique, global id (the URI) - is a Resource. ● Any given Resource can have multiple Representations - these capture the current state of the Resource in a specific format. At the lowest level, the Representation is "a sequence of bytes, plus representation metadata to describe these bytes". Resource & Representation
  • 34.
  • 35.
  • 36.
    36 1. It costsa lot (i.e. expensive, takes time) 2. It’s boring 3. It’s working anyway 4. It’s not my problem, i’m going on vacation for a month Why you shouldn’t write tests
  • 37.
  • 38.
    38 ● Better thanfrequent fire in prod ● Profit for the team ● It’s YOUR problem Why you !!should!! write tests
  • 39.
  • 40.
    40 ● Understanding ofrequirements ● Refactoring insurance ● Documenting features ● Improving API ● Reducing errors Advantages to dev
  • 41.
  • 42.
    42 ● Fast ● Isolated ●Repeatable ● Self-verifying ● Timely F.I.R.S.T. aka SOLID for tests
  • 43.
    43 Keep bugs outof your code
  • 44.
  • 45.
    45 The goal ofintegration testing, is to test whether many separately developed modules work together as expected Goal of Integration Testing
  • 46.
    46 Let’s look closerto notion of integration testing ● narrow integration tests ● broad integration tests
  • 47.
    47 ● exercise onlythat portion of the code in service that talks to a separate service ● uses test mocks/stubs of those services, either in process or remote call ● thus consist of many narrowly scoped tests, often no larger in scope than a unit test (and usually run with the same test framework that's used for unit tests) Narrow integration tests
  • 48.
    48 ● require liveversions of all services, requiring substantial test environment and network access ● exercise code paths through all services, not just code responsible for interactions Broad integration tests
  • 49.
  • 50.
    50 As Summary Если вашапрограмма сделана из говна и палок, то нужно как минимум три типа тестов: на гавно, на палки и интеграционные.
  • 51.
  • 52.
  • 53.
    53 Spring framework offersa comprehensive list of features: ● Spring MVC web application and RESTful web service framework ● Aspect-Oriented Programming including Spring’s declarative transaction management ● Dependency Injection ● Inversion of Control and much more. Spring Features
  • 54.
    54 ● new MyObject()-> IoC container ● Manage object lifecycle What is Inversion of Control
  • 55.
    55 What is DependencyInjection <bean name="customerRepository" class="org.repository.CustomerRepositoryHibernate"/> <bean name="customerService" class="org.service.CustomerServiceImpl"> <property name="customerRepository" ref="customerRepository"></property> </bean> Container that finds a bean, pushes it wherever it is required, and resolves the dependency. We don't look it up ourselves to find them. We are just declaring where we need them.
  • 56.
    56 Confidential about managing dependenciesby selectively inverting key dependencies to prevent fragility of the code & increase usability and stability © Uncle Bob OOP is
  • 57.
    57 ● @Component ● @Repository ●@Service ● @Controller ● @Configuration Spring Stereotypes
  • 58.
    58 Spring beans namingconvention problem
  • 59.
  • 60.
  • 61.
    61 ● WebApplicationContext -web application context which extends ApplicationContext with a contract for accessing the ServletContext. ● Applications usually should not be concerned about those implementation details: the root web application context is simply a centralized place to define shared beans. The root web application context described in the previous section is managed by a listener of class org.springframework.web.context.ContextLoaderListener ● Version 3 of the Servlet API has made configuration through the web.xml file completely optional. Spring Web Contexts - Root Web Context
  • 62.
    62 ● Spring MVCapplications have at least one Dispatcher Servlet configured ● Each DispatcherServlet has an associated application context. Spring Web Contexts - Dispatcher Servlet Context
  • 63.
    63 ● Supports RESTfulURLs ● Annotation based configuration (i.e. developers may reduce the metadata file or less of configuration) ● Flexible in supporting different View types like JSP, Thymeleaf, Velocity, XML, PDF, Tiles etc Advantages of Spring MVC Framework
  • 64.
    64 ● Powerful repositoryand custom object-mapping abstractions ● Dynamic query derivation from repository method names ● Implementation domain base classes providing basic properties ● Support for transparent auditing (created, last changed) ● Possibility to integrate custom repository code ● Easy Spring integration via JavaConfig and custom XML namespaces ● Advanced integration with Spring MVC controllers ● Experimental support for cross-store persistence Spring Data Feature
  • 65.
  • 66.
    66 …… and many more SpringData Query Creation
  • 67.
    67 ● @RequestBody &@ResponseBody ● @RestContoller & @Controller ● @ResponseStatus ● @RequestMapping & @RequestParam ● @PathVariable … > You can customize binding from request to object via HandlerMethodArgumentResolver implementation Spring Rest Annotations
  • 68.
    68 ● @ControllerAdvice ● @ExceptionHandler- only applies to the controller in which it is defined ● RuntimeExceptions are preferable Error Handling @ResponseStatus(HttpStatus.BAD_REQUEST) public class BadRequestException extends RuntimeException { // } @ResponseStatus(HttpStatus.NOT_FOUND) public class ResourceNotFoundException extends RuntimeException { // }
  • 69.
    69 ● Create stand-aloneSpring applications ● Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files) ● Easy Dependency Management & Automatically configure Spring and 3rd party libraries whenever possible ● Provide production-ready features such as metrics, health checks and externalized configuration ● Auto Configuration Spring Boot features
  • 70.
  • 71.
    71 Example: A ->B -> C -> D 1.4 and A -> E -> D 1.0 This example shows that project A depends on B and E. B and E have their own dependencies which encounter different versions of the D artifact. Artifact D 1.0 will be used in the build of A project because the path through E is shorter. Maven BOM
  • 72.
    72 ● @SpringBootApplication ● @EnableAutoConfiguration ●@Conditional and other @ConditionalOn... Spring Boot Annotations
  • 73.
  • 74.
  • 75.
  • 76.
    76 ● SpringRunner forjUnit 4 ● @MockMVC & @WebMvcTest ● @RestClientTest & TestRestTemplate ● @ContextConfiguration & @WebAppConfiguration ● @DataJpaTest & @SpringBootTest ● @TestConfiguration ● @PropertySource ● @ActiveProfiles ● @ContextHierarchy ● @DirtiesContext ● @TestExecutionListeners ● JsonPath ● ….. Spring Test
  • 77.
    77 ● @ContextConfiguration ● @WebAppConfiguration ●@TestConfiguration ● @ActiveProfiles ● @ContextHierarchy ● @PropertySource ● @DirtiesContext Spring Test Configuration
  • 78.
    78 What feeling Ifyou mess up test configuration
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
    85 7. What nextpay attention to
  • 86.
    86 Worth to mentionframeworks to dig in
  • 87.
    87 Worth to mentionframeworks to dig in
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.