SlideShare a Scribd company logo
Testing
Spring-based
apps
Aleksandr Barmin
CONFIDENTIAL | © 2020 EPAM Systems, Inc.
2020 EPAM Systems, Inc.
• Lead Software Engineer
• EPAM Lab Mentor
ALEKSANDR BARMIN
• Email: Aleksandr_Barmin@epam.com
• Twitter: @AlexBarmin
CONTACTS
2
2020 EPAM Systems, Inc.
Agenda
1
6
2
3
4
5
W H Y T E S T I N G I S S O I M P O R T A N T
C O N F I G U R I N G C O N T E X T F O R T E S T S
U S I N G R E A L D E P E N D E N C I E S
E X A M P L E S
3
O V E R V I E W O F T E S T I N G
T E S T L A Y E R S
2020 EPAM Systems, Inc.
Overview of testing
• A test case is a set of test inputs, execution
conditions, and expected results developed for
a particular objective, such as to exercise a
particular program path or to verify
compliance with a specific requirement.
• https://en.wikipedia.org/wiki/Test_case
4
2020 EPAM Systems, Inc.
Test Suite
Overview of testing
5
Test
Test
Test case
System Under
Test (SUT)
Verifies behavior of
2020 EPAM Systems, Inc.
Overview of testing
6
Test runner
Test class
Executes
Test method
Test method
Test method Teardown
Verify
Execute
Setup
Fixture
System Under
Test (SUT)
Configures
Restores
Interact
2020 EPAM Systems, Inc.
Overview of testing
7
Order Controller Order Service
Order Data Access
Object
Orders
Database
How to test it in isolation?
2020 EPAM Systems, Inc.
Overview of testing
8
Slow, complex
test
System Under
Test (SUT)
Dependency
Tests
Fast, simple
test
System Under
Test (SUT)
Test Double
Tests
Replaced with
2020 EPAM Systems, Inc.
Why testing is so important – Test Pyramid
9
End-to-
end
Component
Integration
UnitTest the business logic
Verify that a service
communicates with its
dependencies
Acceptance tests for a
service
Acceptance tests for an
application
Slow, brittle, costly
Fast, reliable, cheap
2020 EPAM Systems, Inc.
Why testing is so important – the Ice Cream Cone
10
End-to-end
Component
Integration
UnitTest the business logic
Verify that a service
communicates with its
dependencies
Acceptance tests for a
service
Acceptance tests for an
application
Slow, brittle, costly
Fast, reliable, cheap
2020 EPAM Systems, Inc.
Deployment pipeline
Why testing is so important - The deployment pipeline
11
Pre-commit
tests
Commit test
stage
Integration
tests stage
Component
tests stage
Deploy stage
Production
environment
Not
production
ready
Production
ready
Fast
feedback
Slow
feedback
2020 EPAM Systems, Inc.
Talk is cheap. Show me the code
- Linus Torvalds
12
2020 EPAM Systems, Inc.
The Blog Application
13
Post Controller Post Service Post Repository Post Database
2020 EPAM Systems, Inc.
Testing The Blog Application
14
Post Controller Post Service Post Repository Post Database
PostServiceSpringTest
2020 EPAM Systems, Inc.
@ContextConfiguration
15
public @interface ContextConfiguration {
}
2020 EPAM Systems, Inc.
@ContextConfiguration
16
public @interface ContextConfiguration {
// where to find bean definitions
String[] value() default {};
String[] locations() default {};
Class<?>[] classes() default {};
}
2020 EPAM Systems, Inc.
@ContextConfiguration
17
public @interface ContextConfiguration {
// where to find bean definitions
String[] value() default {};
String[] locations() default {};
Class<?>[] classes() default {};
// how to initialize the Application Context
Class<? extends ApplicationContextInitializer<?>>[] initializers() default {};
}
2020 EPAM Systems, Inc.
@ContextConfiguration
18
public @interface ContextConfiguration {
// where to find bean definitions
String[] value() default {};
String[] locations() default {};
Class<?>[] classes() default {};
// how to initialize the Application Context
Class<? extends ApplicationContextInitializer<?>>[] initializers() default {};
// should context from parent classes be loaded
boolean inheritLocations() default true;
boolean inheritInitializers() default true;
}
2020 EPAM Systems, Inc.
@ContextConfiguration
19
public @interface ContextConfiguration {
// where to find bean definitions
String[] value() default {};
String[] locations() default {};
Class<?>[] classes() default {};
// how to initialize the Application Context
Class<? extends ApplicationContextInitializer<?>>[] initializers() default {};
// should context from parent classes be loaded
boolean inheritLocations() default true;
boolean inheritInitializers() default true;
// what will read bean definitions
Class<? extends ContextLoader> loader() default ContextLoader.class;
}
2020 EPAM Systems, Inc.
@ContextConfiguration
20
public @interface ContextConfiguration {
// where to find bean definitions
String[] value() default {};
String[] locations() default {};
Class<?>[] classes() default {};
// how to initialize the Application Context
Class<? extends ApplicationContextInitializer<?>>[] initializers() default {};
// should context from parent classes be loaded
boolean inheritLocations() default true;
boolean inheritInitializers() default true;
// what will read bean definitions
Class<? extends ContextLoader> loader() default ContextLoader.class;
// name of the context hierarchy level
String name() default "";
}
2020 EPAM Systems, Inc.
@ContextConfiguration and @SpringJUnitConfig
21
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {
PostService.class,
CommentValidator.class,
PostSanitizer.class
})
public class PostServiceSpringTest { }
@SpringJUnitConfig(classes = {
PostService.class,
CommentValidator.class,
PostSanitizer.class
})
public class PostServiceSpringTest { }
2020 EPAM Systems, Inc.
@SpringBootTest
The search algorithm works up from the package that
contains the test until it finds a
@SpringBootApplication or
@SpringBootConfiguration annotated class. As long as
you’ve structured your code in a sensible way your main
configuration is usually found.
https://docs.spring.io/spring-
boot/docs/1.5.2.RELEASE/reference/html/boot-features-
testing.html#boot-features-testing-spring-boot-
applications-detecting-config
22
2020 EPAM Systems, Inc.
@SpringBootTest
23
Looks for
@SpringBootApplication or
@SpringBootConfiguration
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(…)
public @interface SpringBootApplication { }
@SpringBootConfiguration
@Configuration
@TestConfiguration
PostControllerSpringBootTest
2020 EPAM Systems, Inc.
@Sql, @SqlConfig and JdbcTestUtils
24
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class PostControllerWithDbInitTest {
}
2020 EPAM Systems, Inc.
@Sql, @SqlConfig and JdbcTestUtils
25
@Sql(
scripts = "/create_posts.sql",
config = @SqlConfig(separator = ";")
)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class PostControllerWithDbInitTest {
}
2020 EPAM Systems, Inc.
@Sql, @SqlConfig and JdbcTestUtils
26
@Sql(
scripts = "/create_posts.sql",
config = @SqlConfig(separator = ";")
)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class PostControllerWithDbInitTest {
@Test
@Sql("/create_special_post.sql")
void findOne_shouldFindSpecialPost() {
// ...
}
}
ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
populator.addScripts(new ClassPathResource("test-schema.sql"));
populator.setSeparator("@@");
populator.execute(this.dataSource);
2020 EPAM Systems, Inc.
@Sql, @SqlConfig and JdbcTestUtils
27
@Sql(
scripts = "/create_posts.sql",
config = @SqlConfig(separator = ";")
)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class PostControllerWithDbInitTest {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
@Sql("/create_special_post.sql")
void findOne_shouldFindSpecialPost() {
final int postCount = JdbcTestUtils.countRowsInTable(jdbcTemplate, "POSTS");
assertTrue(postCount > 0);
// ...
}
}
PostControllerWithDbInitTest
2020 EPAM Systems, Inc.
Testing The Blog Application
28
Post Controller Post Service Post Repository Post Database
REST client
2020 EPAM Systems, Inc.
Test layers - @JsonTest
• @JsonTest:
• CacheAutoConfiguration
• GsonAutoConfiguration
• JacksonAutoConfiguration
• JsonTestAutoConfiguration
29
PostControllerJsonTest
2020 EPAM Systems, Inc.
Testing The Blog Application
30
Post Controller Post Service Post Repository Post Database
Web Client
2020 EPAM Systems, Inc.
Test layers - @WebMvcTest
• @WebMvcTest:
• CacheAutoConfiguration
• MessageSourceAutoConfiguration
• HypermediaAutoConfiguration
• JacksonAutoConfiguration
• ThymeleafAutoConfiguration (*)
• ValidationAutoConfiguration
• ErrorMvcAutConfiguration
• HttpMessageConvertersAutoConfiguration
• ServerPropertiesAutoConfiguration
• WebMvcAutoConfiguration
• MockMvc(*)AutoConfiguration
31
PostControllerWebMvcTest, AdminControllerHtmlTest
2020 EPAM Systems, Inc.
Testing The Blog Application
32
Post Controller Post Service Post Repository Post Database
2020 EPAM Systems, Inc.
Test layers - @DataJpaTest
• @DataJpaTest:
• CacheAutoConfiguration
• JpaRepositoriesAutoConfiguration
• FlywayAutoConfiguration
• DataSourceAutoConfiguration
• DataSourceTransactionManagerAC
• JdbcTemplateAutoConfiguration
• HibernateJpaAutoConfiguration
• TransactionAutoConfiguration
• TestDatabaseAutoConfiguration
• TestEntityManagerAutoConfiguration
33
PostRepositoryDataJpaTest
2020 EPAM Systems, Inc.
Testing The Blog Application
34
Post Controller Post Service Post Repository Post Database
2020 EPAM Systems, Inc.
Test layers - @JdbcTest
• @JdbcTest:
• CacheAutoConfiguration
• FlywayAutoConfiguration
• DataSourceAutoConfiguration
• DataSourceTransactionManagerAC
• JdbcTemplateAutoConfiguration
• TransactionAutoConfiguration
• TestDatabaseAutoConfiguration
35
PostJdbcTest
2020 EPAM Systems, Inc.
Testing The Blog Application
36
Post Controller Post Service Post Repository Post Database
External REST
Service
2020 EPAM Systems, Inc.
Test layers - @RestClientTest
• @RestClientTest:
• CacheAutoConfiguration
• JacksonAutoConfiguration
• HttpMessageConverterAutoConfiguration
• WebClientAutoConfiguration
• MockRestServiceServerAutoConfiguration
• WebClientRestTemplateAutoConfiguration
37
PostImporterRestClientTest
2020 EPAM Systems, Inc.
Testing The Blog Application
38
Post Controller Post Service Post Repository
Mock or in-
memory
database
2020 EPAM Systems, Inc.
Docker Container
Testing The Blog Application
39
Post Controller Post Service Post Repository
Real DB
instance
Mock or in-
memory
database
2020 EPAM Systems, Inc.
TestContainers
• Integration tests with real dependencies in Docker
containers instead of mocks:
• Databases
• Message queues
• Browsers
• Anything else that could be run in Docker
• https://www.testcontainers.org/
40
PostServiceTestContainersTest
2020 EPAM Systems, Inc.
Examples weren’t shown
• @DertiesContext
• @ActiveProfiles
• @ContextHierarchy
• ReflectionTestUtils
• EnvironmentTestUtils
• Spring Cloud Contract
• Spring Cloud Stream Test
41
2020 EPAM Systems, Inc.
Conclusion
• Follow the Test Pyramid approach
• Use FIRST for tests
• Use SOLID for your code
• Spring Framework has a lot of tools that simplify
testing – use them
• https://github.com/aabarmin/epam-spring-testing
• https://docs.spring.io/spring/docs/current/spring-
framework-reference/testing.html
• https://docs.spring.io/spring-
boot/docs/1.5.2.RELEASE/reference/html/boot-
features-testing.html
• https://www.testcontainers.org/
• https://spring.io/projects/spring-cloud-contract
• https://cloud.spring.io/spring-cloud-static/spring-
cloud-
stream/2.1.3.RELEASE/multi/multi__testing.html
42
Thank you!
CONFIDENTIAL | © 2019 EPAM Systems, Inc.
QUESTIONS?
43

More Related Content

What's hot

08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata
rehaniltifat
 
Add (Syntactic) Sugar To Your Java
Add (Syntactic) Sugar To Your JavaAdd (Syntactic) Sugar To Your Java
Add (Syntactic) Sugar To Your Java
Pascal-Louis Perez
 
Oracle Enterprise Repository
Oracle Enterprise RepositoryOracle Enterprise Repository
Oracle Enterprise Repository
Prabhat gangwar
 
L2C Benchmarks, or how I learned to stop worrying and love JMH
L2C Benchmarks, or how I learned to stop worrying and love JMHL2C Benchmarks, or how I learned to stop worrying and love JMH
L2C Benchmarks, or how I learned to stop worrying and love JMH
Andres Almiray
 
EMC Documentum - xCP 2.x Updating Java Services
EMC Documentum - xCP 2.x Updating Java ServicesEMC Documentum - xCP 2.x Updating Java Services
EMC Documentum - xCP 2.x Updating Java Services
Haytham Ghandour
 
06 Using More Package Concepts
06 Using More Package Concepts06 Using More Package Concepts
06 Using More Package Concepts
rehaniltifat
 
Colvin exadata and_oem12c
Colvin exadata and_oem12cColvin exadata and_oem12c
Colvin exadata and_oem12cEnkitec
 
EMC Documentum xCP 2.2 Self Paced Tutorial v1.0
EMC Documentum xCP 2.2 Self Paced Tutorial v1.0EMC Documentum xCP 2.2 Self Paced Tutorial v1.0
EMC Documentum xCP 2.2 Self Paced Tutorial v1.0
Haytham Ghandour
 
EMC Documentum - xCP.x Updating Endpoint
EMC Documentum - xCP.x Updating EndpointEMC Documentum - xCP.x Updating Endpoint
EMC Documentum - xCP.x Updating Endpoint
Haytham Ghandour
 
Polymorphic Table Functions in SQL
Polymorphic Table Functions in SQLPolymorphic Table Functions in SQL
Polymorphic Table Functions in SQL
Chris Saxon
 
1 z0 060 - oracle certification
1 z0 060 - oracle certification1 z0 060 - oracle certification
1 z0 060 - oracle certification
adam_jhon
 
PerkinElmer_UAT_Testcase_Analytics
PerkinElmer_UAT_Testcase_AnalyticsPerkinElmer_UAT_Testcase_Analytics
PerkinElmer_UAT_Testcase_AnalyticsEthan Ferrari
 
Reviving the HTTP Service - Felix Meschberger
Reviving the HTTP Service - Felix MeschbergerReviving the HTTP Service - Felix Meschberger
Reviving the HTTP Service - Felix Meschberger
mfrancis
 
Testing soa, web services and application development framework applications
Testing soa, web services and application development framework applicationsTesting soa, web services and application development framework applications
Testing soa, web services and application development framework applicationsInSync Conference
 

What's hot (14)

08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata
 
Add (Syntactic) Sugar To Your Java
Add (Syntactic) Sugar To Your JavaAdd (Syntactic) Sugar To Your Java
Add (Syntactic) Sugar To Your Java
 
Oracle Enterprise Repository
Oracle Enterprise RepositoryOracle Enterprise Repository
Oracle Enterprise Repository
 
L2C Benchmarks, or how I learned to stop worrying and love JMH
L2C Benchmarks, or how I learned to stop worrying and love JMHL2C Benchmarks, or how I learned to stop worrying and love JMH
L2C Benchmarks, or how I learned to stop worrying and love JMH
 
EMC Documentum - xCP 2.x Updating Java Services
EMC Documentum - xCP 2.x Updating Java ServicesEMC Documentum - xCP 2.x Updating Java Services
EMC Documentum - xCP 2.x Updating Java Services
 
06 Using More Package Concepts
06 Using More Package Concepts06 Using More Package Concepts
06 Using More Package Concepts
 
Colvin exadata and_oem12c
Colvin exadata and_oem12cColvin exadata and_oem12c
Colvin exadata and_oem12c
 
EMC Documentum xCP 2.2 Self Paced Tutorial v1.0
EMC Documentum xCP 2.2 Self Paced Tutorial v1.0EMC Documentum xCP 2.2 Self Paced Tutorial v1.0
EMC Documentum xCP 2.2 Self Paced Tutorial v1.0
 
EMC Documentum - xCP.x Updating Endpoint
EMC Documentum - xCP.x Updating EndpointEMC Documentum - xCP.x Updating Endpoint
EMC Documentum - xCP.x Updating Endpoint
 
Polymorphic Table Functions in SQL
Polymorphic Table Functions in SQLPolymorphic Table Functions in SQL
Polymorphic Table Functions in SQL
 
1 z0 060 - oracle certification
1 z0 060 - oracle certification1 z0 060 - oracle certification
1 z0 060 - oracle certification
 
PerkinElmer_UAT_Testcase_Analytics
PerkinElmer_UAT_Testcase_AnalyticsPerkinElmer_UAT_Testcase_Analytics
PerkinElmer_UAT_Testcase_Analytics
 
Reviving the HTTP Service - Felix Meschberger
Reviving the HTTP Service - Felix MeschbergerReviving the HTTP Service - Felix Meschberger
Reviving the HTTP Service - Felix Meschberger
 
Testing soa, web services and application development framework applications
Testing soa, web services and application development framework applicationsTesting soa, web services and application development framework applications
Testing soa, web services and application development framework applications
 

Similar to Тестирование Spring-based приложений

Testing Your Application On Google App Engine
Testing Your Application On Google App EngineTesting Your Application On Google App Engine
Testing Your Application On Google App Engine
IndicThreads
 
Testing your application on Google App Engine
Testing your application on Google App EngineTesting your application on Google App Engine
Testing your application on Google App Engine
Inphina Technologies
 
Testing for fun in production Into The Box 2018
Testing for fun in production Into The Box 2018Testing for fun in production Into The Box 2018
Testing for fun in production Into The Box 2018
Ortus Solutions, Corp
 
Spring batch for large enterprises operations
Spring batch for large enterprises operations Spring batch for large enterprises operations
Spring batch for large enterprises operations
Ignasi González
 
Spring Testing, Fight for the Context
Spring Testing, Fight for the ContextSpring Testing, Fight for the Context
Spring Testing, Fight for the Context
GlobalLogic Ukraine
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
ciklum_ods
 
How to make a Load Testing with Visual Studio 2012
How to make a Load Testing with Visual Studio 2012How to make a Load Testing with Visual Studio 2012
How to make a Load Testing with Visual Studio 2012
Chen-Tien Tsai
 
Defensive Apex Programming
Defensive Apex ProgrammingDefensive Apex Programming
Defensive Apex Programming
Salesforce Developers
 
Apache Aries Blog Sample
Apache Aries Blog SampleApache Aries Blog Sample
Apache Aries Blog Sample
Skills Matter
 
Deep Dive - CI/CD on AWS
Deep Dive - CI/CD on AWSDeep Dive - CI/CD on AWS
Deep Dive - CI/CD on AWS
Amazon Web Services
 
APIdays Helsinki 2019 - API Versioning with REST, JSON and Swagger with Thoma...
APIdays Helsinki 2019 - API Versioning with REST, JSON and Swagger with Thoma...APIdays Helsinki 2019 - API Versioning with REST, JSON and Swagger with Thoma...
APIdays Helsinki 2019 - API Versioning with REST, JSON and Swagger with Thoma...
apidays
 
Making your managed package extensible with Apex Plugins
Making your managed package extensible with Apex PluginsMaking your managed package extensible with Apex Plugins
Making your managed package extensible with Apex Plugins
Stephen Willcock
 
Data Seeding via Parameterized API Requests
Data Seeding via Parameterized API RequestsData Seeding via Parameterized API Requests
Data Seeding via Parameterized API Requests
RapidValue
 
Spring Cloud Function — Going Serverless
Spring Cloud Function — Going ServerlessSpring Cloud Function — Going Serverless
Spring Cloud Function — Going Serverless
GlobalLogic Ukraine
 
Robustness testing
Robustness testingRobustness testing
Robustness testing
CS, NcState
 
Spring Cloud Data Flow Overview
Spring Cloud Data Flow OverviewSpring Cloud Data Flow Overview
Spring Cloud Data Flow Overview
VMware Tanzu
 
ITGM8. Всеволод Брекелов (Grid Dinamics) Component tests. let's do that!
ITGM8. Всеволод Брекелов (Grid Dinamics) Component tests. let's do that!ITGM8. Всеволод Брекелов (Grid Dinamics) Component tests. let's do that!
ITGM8. Всеволод Брекелов (Grid Dinamics) Component tests. let's do that!
SPB SQA Group
 
Stac.report.platform.symphony.hadoop.comparison.111212
Stac.report.platform.symphony.hadoop.comparison.111212Stac.report.platform.symphony.hadoop.comparison.111212
Stac.report.platform.symphony.hadoop.comparison.111212Accenture
 
Appium Automation with Kotlin
Appium Automation with KotlinAppium Automation with Kotlin
Appium Automation with Kotlin
RapidValue
 
Enterprise Ready Test Execution Platform for Mobile Apps
Enterprise Ready Test Execution Platform for Mobile AppsEnterprise Ready Test Execution Platform for Mobile Apps
Enterprise Ready Test Execution Platform for Mobile Apps
Vijayan Srinivasan
 

Similar to Тестирование Spring-based приложений (20)

Testing Your Application On Google App Engine
Testing Your Application On Google App EngineTesting Your Application On Google App Engine
Testing Your Application On Google App Engine
 
Testing your application on Google App Engine
Testing your application on Google App EngineTesting your application on Google App Engine
Testing your application on Google App Engine
 
Testing for fun in production Into The Box 2018
Testing for fun in production Into The Box 2018Testing for fun in production Into The Box 2018
Testing for fun in production Into The Box 2018
 
Spring batch for large enterprises operations
Spring batch for large enterprises operations Spring batch for large enterprises operations
Spring batch for large enterprises operations
 
Spring Testing, Fight for the Context
Spring Testing, Fight for the ContextSpring Testing, Fight for the Context
Spring Testing, Fight for the Context
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
How to make a Load Testing with Visual Studio 2012
How to make a Load Testing with Visual Studio 2012How to make a Load Testing with Visual Studio 2012
How to make a Load Testing with Visual Studio 2012
 
Defensive Apex Programming
Defensive Apex ProgrammingDefensive Apex Programming
Defensive Apex Programming
 
Apache Aries Blog Sample
Apache Aries Blog SampleApache Aries Blog Sample
Apache Aries Blog Sample
 
Deep Dive - CI/CD on AWS
Deep Dive - CI/CD on AWSDeep Dive - CI/CD on AWS
Deep Dive - CI/CD on AWS
 
APIdays Helsinki 2019 - API Versioning with REST, JSON and Swagger with Thoma...
APIdays Helsinki 2019 - API Versioning with REST, JSON and Swagger with Thoma...APIdays Helsinki 2019 - API Versioning with REST, JSON and Swagger with Thoma...
APIdays Helsinki 2019 - API Versioning with REST, JSON and Swagger with Thoma...
 
Making your managed package extensible with Apex Plugins
Making your managed package extensible with Apex PluginsMaking your managed package extensible with Apex Plugins
Making your managed package extensible with Apex Plugins
 
Data Seeding via Parameterized API Requests
Data Seeding via Parameterized API RequestsData Seeding via Parameterized API Requests
Data Seeding via Parameterized API Requests
 
Spring Cloud Function — Going Serverless
Spring Cloud Function — Going ServerlessSpring Cloud Function — Going Serverless
Spring Cloud Function — Going Serverless
 
Robustness testing
Robustness testingRobustness testing
Robustness testing
 
Spring Cloud Data Flow Overview
Spring Cloud Data Flow OverviewSpring Cloud Data Flow Overview
Spring Cloud Data Flow Overview
 
ITGM8. Всеволод Брекелов (Grid Dinamics) Component tests. let's do that!
ITGM8. Всеволод Брекелов (Grid Dinamics) Component tests. let's do that!ITGM8. Всеволод Брекелов (Grid Dinamics) Component tests. let's do that!
ITGM8. Всеволод Брекелов (Grid Dinamics) Component tests. let's do that!
 
Stac.report.platform.symphony.hadoop.comparison.111212
Stac.report.platform.symphony.hadoop.comparison.111212Stac.report.platform.symphony.hadoop.comparison.111212
Stac.report.platform.symphony.hadoop.comparison.111212
 
Appium Automation with Kotlin
Appium Automation with KotlinAppium Automation with Kotlin
Appium Automation with Kotlin
 
Enterprise Ready Test Execution Platform for Mobile Apps
Enterprise Ready Test Execution Platform for Mobile AppsEnterprise Ready Test Execution Platform for Mobile Apps
Enterprise Ready Test Execution Platform for Mobile Apps
 

More from Vitebsk Miniq

Runtime compilation and code execution in groovy
Runtime compilation and code execution in groovyRuntime compilation and code execution in groovy
Runtime compilation and code execution in groovy
Vitebsk Miniq
 
The 5 Laws of Software Estimates
The 5 Laws of Software EstimatesThe 5 Laws of Software Estimates
The 5 Laws of Software Estimates
Vitebsk Miniq
 
Latest & Greatest Observability Release 7.9
Latest & Greatest Observability Release 7.9Latest & Greatest Observability Release 7.9
Latest & Greatest Observability Release 7.9
Vitebsk Miniq
 
Семантический поиск - что это, как работает и чем отличается от просто поиска
Семантический поиск - что это, как работает и чем отличается от просто поискаСемантический поиск - что это, как работает и чем отличается от просто поиска
Семантический поиск - что это, как работает и чем отличается от просто поиска
Vitebsk Miniq
 
Локализационное тестирование - это не только перевод
Локализационное тестирование - это не только переводЛокализационное тестирование - это не только перевод
Локализационное тестирование - это не только перевод
Vitebsk Miniq
 
ISTQB Сертификация тестировщиков: быть или не быть?
ISTQB Сертификация тестировщиков: быть или не быть?ISTQB Сертификация тестировщиков: быть или не быть?
ISTQB Сертификация тестировщиков: быть или не быть?
Vitebsk Miniq
 
Apollo GraphQL Federation
Apollo GraphQL FederationApollo GraphQL Federation
Apollo GraphQL Federation
Vitebsk Miniq
 
Who is a functional tester
Who is a functional testerWho is a functional tester
Who is a functional tester
Vitebsk Miniq
 
Crawling healthy
Crawling healthyCrawling healthy
Crawling healthy
Vitebsk Miniq
 
Вперед в прошлое
Вперед в прошлоеВперед в прошлое
Вперед в прошлое
Vitebsk Miniq
 
CloudFormation experience
CloudFormation experienceCloudFormation experience
CloudFormation experience
Vitebsk Miniq
 
Learning Intelligence: the story of mine
Learning Intelligence: the story of mineLearning Intelligence: the story of mine
Learning Intelligence: the story of mine
Vitebsk Miniq
 
Как программисты могут спасти мир
Как программисты могут спасти мирКак программисты могут спасти мир
Как программисты могут спасти мир
Vitebsk Miniq
 
Использование AzureDevOps при разработке микросервисных приложений
Использование AzureDevOps при разработке микросервисных приложенийИспользование AzureDevOps при разработке микросервисных приложений
Использование AzureDevOps при разработке микросервисных приложений
Vitebsk Miniq
 
Distributed tracing system in action. Instana Tracing.
Distributed tracing system in action. Instana Tracing.Distributed tracing system in action. Instana Tracing.
Distributed tracing system in action. Instana Tracing.
Vitebsk Miniq
 
Насорил - убери!
Насорил - убери!Насорил - убери!
Насорил - убери!
Vitebsk Miniq
 
Styled-components. Что? Когда? И зачем?
Styled-components. Что? Когда? И зачем?Styled-components. Что? Когда? И зачем?
Styled-components. Что? Когда? И зачем?
Vitebsk Miniq
 
Красные флаги и розовые очки
Красные флаги и розовые очкиКрасные флаги и розовые очки
Красные флаги и розовые очки
Vitebsk Miniq
 
CSS. Практика
CSS. ПрактикаCSS. Практика
CSS. Практика
Vitebsk Miniq
 
Разделяй и властвуй!
Разделяй и властвуй!Разделяй и властвуй!
Разделяй и властвуй!
Vitebsk Miniq
 

More from Vitebsk Miniq (20)

Runtime compilation and code execution in groovy
Runtime compilation and code execution in groovyRuntime compilation and code execution in groovy
Runtime compilation and code execution in groovy
 
The 5 Laws of Software Estimates
The 5 Laws of Software EstimatesThe 5 Laws of Software Estimates
The 5 Laws of Software Estimates
 
Latest & Greatest Observability Release 7.9
Latest & Greatest Observability Release 7.9Latest & Greatest Observability Release 7.9
Latest & Greatest Observability Release 7.9
 
Семантический поиск - что это, как работает и чем отличается от просто поиска
Семантический поиск - что это, как работает и чем отличается от просто поискаСемантический поиск - что это, как работает и чем отличается от просто поиска
Семантический поиск - что это, как работает и чем отличается от просто поиска
 
Локализационное тестирование - это не только перевод
Локализационное тестирование - это не только переводЛокализационное тестирование - это не только перевод
Локализационное тестирование - это не только перевод
 
ISTQB Сертификация тестировщиков: быть или не быть?
ISTQB Сертификация тестировщиков: быть или не быть?ISTQB Сертификация тестировщиков: быть или не быть?
ISTQB Сертификация тестировщиков: быть или не быть?
 
Apollo GraphQL Federation
Apollo GraphQL FederationApollo GraphQL Federation
Apollo GraphQL Federation
 
Who is a functional tester
Who is a functional testerWho is a functional tester
Who is a functional tester
 
Crawling healthy
Crawling healthyCrawling healthy
Crawling healthy
 
Вперед в прошлое
Вперед в прошлоеВперед в прошлое
Вперед в прошлое
 
CloudFormation experience
CloudFormation experienceCloudFormation experience
CloudFormation experience
 
Learning Intelligence: the story of mine
Learning Intelligence: the story of mineLearning Intelligence: the story of mine
Learning Intelligence: the story of mine
 
Как программисты могут спасти мир
Как программисты могут спасти мирКак программисты могут спасти мир
Как программисты могут спасти мир
 
Использование AzureDevOps при разработке микросервисных приложений
Использование AzureDevOps при разработке микросервисных приложенийИспользование AzureDevOps при разработке микросервисных приложений
Использование AzureDevOps при разработке микросервисных приложений
 
Distributed tracing system in action. Instana Tracing.
Distributed tracing system in action. Instana Tracing.Distributed tracing system in action. Instana Tracing.
Distributed tracing system in action. Instana Tracing.
 
Насорил - убери!
Насорил - убери!Насорил - убери!
Насорил - убери!
 
Styled-components. Что? Когда? И зачем?
Styled-components. Что? Когда? И зачем?Styled-components. Что? Когда? И зачем?
Styled-components. Что? Когда? И зачем?
 
Красные флаги и розовые очки
Красные флаги и розовые очкиКрасные флаги и розовые очки
Красные флаги и розовые очки
 
CSS. Практика
CSS. ПрактикаCSS. Практика
CSS. Практика
 
Разделяй и властвуй!
Разделяй и властвуй!Разделяй и властвуй!
Разделяй и властвуй!
 

Recently uploaded

UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...
Zilliz
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 

Recently uploaded (20)

UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 

Тестирование Spring-based приложений

  • 2. 2020 EPAM Systems, Inc. • Lead Software Engineer • EPAM Lab Mentor ALEKSANDR BARMIN • Email: Aleksandr_Barmin@epam.com • Twitter: @AlexBarmin CONTACTS 2
  • 3. 2020 EPAM Systems, Inc. Agenda 1 6 2 3 4 5 W H Y T E S T I N G I S S O I M P O R T A N T C O N F I G U R I N G C O N T E X T F O R T E S T S U S I N G R E A L D E P E N D E N C I E S E X A M P L E S 3 O V E R V I E W O F T E S T I N G T E S T L A Y E R S
  • 4. 2020 EPAM Systems, Inc. Overview of testing • A test case is a set of test inputs, execution conditions, and expected results developed for a particular objective, such as to exercise a particular program path or to verify compliance with a specific requirement. • https://en.wikipedia.org/wiki/Test_case 4
  • 5. 2020 EPAM Systems, Inc. Test Suite Overview of testing 5 Test Test Test case System Under Test (SUT) Verifies behavior of
  • 6. 2020 EPAM Systems, Inc. Overview of testing 6 Test runner Test class Executes Test method Test method Test method Teardown Verify Execute Setup Fixture System Under Test (SUT) Configures Restores Interact
  • 7. 2020 EPAM Systems, Inc. Overview of testing 7 Order Controller Order Service Order Data Access Object Orders Database How to test it in isolation?
  • 8. 2020 EPAM Systems, Inc. Overview of testing 8 Slow, complex test System Under Test (SUT) Dependency Tests Fast, simple test System Under Test (SUT) Test Double Tests Replaced with
  • 9. 2020 EPAM Systems, Inc. Why testing is so important – Test Pyramid 9 End-to- end Component Integration UnitTest the business logic Verify that a service communicates with its dependencies Acceptance tests for a service Acceptance tests for an application Slow, brittle, costly Fast, reliable, cheap
  • 10. 2020 EPAM Systems, Inc. Why testing is so important – the Ice Cream Cone 10 End-to-end Component Integration UnitTest the business logic Verify that a service communicates with its dependencies Acceptance tests for a service Acceptance tests for an application Slow, brittle, costly Fast, reliable, cheap
  • 11. 2020 EPAM Systems, Inc. Deployment pipeline Why testing is so important - The deployment pipeline 11 Pre-commit tests Commit test stage Integration tests stage Component tests stage Deploy stage Production environment Not production ready Production ready Fast feedback Slow feedback
  • 12. 2020 EPAM Systems, Inc. Talk is cheap. Show me the code - Linus Torvalds 12
  • 13. 2020 EPAM Systems, Inc. The Blog Application 13 Post Controller Post Service Post Repository Post Database
  • 14. 2020 EPAM Systems, Inc. Testing The Blog Application 14 Post Controller Post Service Post Repository Post Database PostServiceSpringTest
  • 15. 2020 EPAM Systems, Inc. @ContextConfiguration 15 public @interface ContextConfiguration { }
  • 16. 2020 EPAM Systems, Inc. @ContextConfiguration 16 public @interface ContextConfiguration { // where to find bean definitions String[] value() default {}; String[] locations() default {}; Class<?>[] classes() default {}; }
  • 17. 2020 EPAM Systems, Inc. @ContextConfiguration 17 public @interface ContextConfiguration { // where to find bean definitions String[] value() default {}; String[] locations() default {}; Class<?>[] classes() default {}; // how to initialize the Application Context Class<? extends ApplicationContextInitializer<?>>[] initializers() default {}; }
  • 18. 2020 EPAM Systems, Inc. @ContextConfiguration 18 public @interface ContextConfiguration { // where to find bean definitions String[] value() default {}; String[] locations() default {}; Class<?>[] classes() default {}; // how to initialize the Application Context Class<? extends ApplicationContextInitializer<?>>[] initializers() default {}; // should context from parent classes be loaded boolean inheritLocations() default true; boolean inheritInitializers() default true; }
  • 19. 2020 EPAM Systems, Inc. @ContextConfiguration 19 public @interface ContextConfiguration { // where to find bean definitions String[] value() default {}; String[] locations() default {}; Class<?>[] classes() default {}; // how to initialize the Application Context Class<? extends ApplicationContextInitializer<?>>[] initializers() default {}; // should context from parent classes be loaded boolean inheritLocations() default true; boolean inheritInitializers() default true; // what will read bean definitions Class<? extends ContextLoader> loader() default ContextLoader.class; }
  • 20. 2020 EPAM Systems, Inc. @ContextConfiguration 20 public @interface ContextConfiguration { // where to find bean definitions String[] value() default {}; String[] locations() default {}; Class<?>[] classes() default {}; // how to initialize the Application Context Class<? extends ApplicationContextInitializer<?>>[] initializers() default {}; // should context from parent classes be loaded boolean inheritLocations() default true; boolean inheritInitializers() default true; // what will read bean definitions Class<? extends ContextLoader> loader() default ContextLoader.class; // name of the context hierarchy level String name() default ""; }
  • 21. 2020 EPAM Systems, Inc. @ContextConfiguration and @SpringJUnitConfig 21 @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = { PostService.class, CommentValidator.class, PostSanitizer.class }) public class PostServiceSpringTest { } @SpringJUnitConfig(classes = { PostService.class, CommentValidator.class, PostSanitizer.class }) public class PostServiceSpringTest { }
  • 22. 2020 EPAM Systems, Inc. @SpringBootTest The search algorithm works up from the package that contains the test until it finds a @SpringBootApplication or @SpringBootConfiguration annotated class. As long as you’ve structured your code in a sensible way your main configuration is usually found. https://docs.spring.io/spring- boot/docs/1.5.2.RELEASE/reference/html/boot-features- testing.html#boot-features-testing-spring-boot- applications-detecting-config 22
  • 23. 2020 EPAM Systems, Inc. @SpringBootTest 23 Looks for @SpringBootApplication or @SpringBootConfiguration @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan(…) public @interface SpringBootApplication { } @SpringBootConfiguration @Configuration @TestConfiguration PostControllerSpringBootTest
  • 24. 2020 EPAM Systems, Inc. @Sql, @SqlConfig and JdbcTestUtils 24 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) class PostControllerWithDbInitTest { }
  • 25. 2020 EPAM Systems, Inc. @Sql, @SqlConfig and JdbcTestUtils 25 @Sql( scripts = "/create_posts.sql", config = @SqlConfig(separator = ";") ) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) class PostControllerWithDbInitTest { }
  • 26. 2020 EPAM Systems, Inc. @Sql, @SqlConfig and JdbcTestUtils 26 @Sql( scripts = "/create_posts.sql", config = @SqlConfig(separator = ";") ) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) class PostControllerWithDbInitTest { @Test @Sql("/create_special_post.sql") void findOne_shouldFindSpecialPost() { // ... } } ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); populator.addScripts(new ClassPathResource("test-schema.sql")); populator.setSeparator("@@"); populator.execute(this.dataSource);
  • 27. 2020 EPAM Systems, Inc. @Sql, @SqlConfig and JdbcTestUtils 27 @Sql( scripts = "/create_posts.sql", config = @SqlConfig(separator = ";") ) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) class PostControllerWithDbInitTest { @Autowired private JdbcTemplate jdbcTemplate; @Test @Sql("/create_special_post.sql") void findOne_shouldFindSpecialPost() { final int postCount = JdbcTestUtils.countRowsInTable(jdbcTemplate, "POSTS"); assertTrue(postCount > 0); // ... } } PostControllerWithDbInitTest
  • 28. 2020 EPAM Systems, Inc. Testing The Blog Application 28 Post Controller Post Service Post Repository Post Database REST client
  • 29. 2020 EPAM Systems, Inc. Test layers - @JsonTest • @JsonTest: • CacheAutoConfiguration • GsonAutoConfiguration • JacksonAutoConfiguration • JsonTestAutoConfiguration 29 PostControllerJsonTest
  • 30. 2020 EPAM Systems, Inc. Testing The Blog Application 30 Post Controller Post Service Post Repository Post Database Web Client
  • 31. 2020 EPAM Systems, Inc. Test layers - @WebMvcTest • @WebMvcTest: • CacheAutoConfiguration • MessageSourceAutoConfiguration • HypermediaAutoConfiguration • JacksonAutoConfiguration • ThymeleafAutoConfiguration (*) • ValidationAutoConfiguration • ErrorMvcAutConfiguration • HttpMessageConvertersAutoConfiguration • ServerPropertiesAutoConfiguration • WebMvcAutoConfiguration • MockMvc(*)AutoConfiguration 31 PostControllerWebMvcTest, AdminControllerHtmlTest
  • 32. 2020 EPAM Systems, Inc. Testing The Blog Application 32 Post Controller Post Service Post Repository Post Database
  • 33. 2020 EPAM Systems, Inc. Test layers - @DataJpaTest • @DataJpaTest: • CacheAutoConfiguration • JpaRepositoriesAutoConfiguration • FlywayAutoConfiguration • DataSourceAutoConfiguration • DataSourceTransactionManagerAC • JdbcTemplateAutoConfiguration • HibernateJpaAutoConfiguration • TransactionAutoConfiguration • TestDatabaseAutoConfiguration • TestEntityManagerAutoConfiguration 33 PostRepositoryDataJpaTest
  • 34. 2020 EPAM Systems, Inc. Testing The Blog Application 34 Post Controller Post Service Post Repository Post Database
  • 35. 2020 EPAM Systems, Inc. Test layers - @JdbcTest • @JdbcTest: • CacheAutoConfiguration • FlywayAutoConfiguration • DataSourceAutoConfiguration • DataSourceTransactionManagerAC • JdbcTemplateAutoConfiguration • TransactionAutoConfiguration • TestDatabaseAutoConfiguration 35 PostJdbcTest
  • 36. 2020 EPAM Systems, Inc. Testing The Blog Application 36 Post Controller Post Service Post Repository Post Database External REST Service
  • 37. 2020 EPAM Systems, Inc. Test layers - @RestClientTest • @RestClientTest: • CacheAutoConfiguration • JacksonAutoConfiguration • HttpMessageConverterAutoConfiguration • WebClientAutoConfiguration • MockRestServiceServerAutoConfiguration • WebClientRestTemplateAutoConfiguration 37 PostImporterRestClientTest
  • 38. 2020 EPAM Systems, Inc. Testing The Blog Application 38 Post Controller Post Service Post Repository Mock or in- memory database
  • 39. 2020 EPAM Systems, Inc. Docker Container Testing The Blog Application 39 Post Controller Post Service Post Repository Real DB instance Mock or in- memory database
  • 40. 2020 EPAM Systems, Inc. TestContainers • Integration tests with real dependencies in Docker containers instead of mocks: • Databases • Message queues • Browsers • Anything else that could be run in Docker • https://www.testcontainers.org/ 40 PostServiceTestContainersTest
  • 41. 2020 EPAM Systems, Inc. Examples weren’t shown • @DertiesContext • @ActiveProfiles • @ContextHierarchy • ReflectionTestUtils • EnvironmentTestUtils • Spring Cloud Contract • Spring Cloud Stream Test 41
  • 42. 2020 EPAM Systems, Inc. Conclusion • Follow the Test Pyramid approach • Use FIRST for tests • Use SOLID for your code • Spring Framework has a lot of tools that simplify testing – use them • https://github.com/aabarmin/epam-spring-testing • https://docs.spring.io/spring/docs/current/spring- framework-reference/testing.html • https://docs.spring.io/spring- boot/docs/1.5.2.RELEASE/reference/html/boot- features-testing.html • https://www.testcontainers.org/ • https://spring.io/projects/spring-cloud-contract • https://cloud.spring.io/spring-cloud-static/spring- cloud- stream/2.1.3.RELEASE/multi/multi__testing.html 42 Thank you!
  • 43. CONFIDENTIAL | © 2019 EPAM Systems, Inc. QUESTIONS? 43