SlideShare uma empresa Scribd logo
1 de 43
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadatarehaniltifat
 
Add (Syntactic) Sugar To Your Java
Add (Syntactic) Sugar To Your JavaAdd (Syntactic) Sugar To Your Java
Add (Syntactic) Sugar To Your JavaPascal-Louis Perez
 
Oracle Enterprise Repository
Oracle Enterprise RepositoryOracle Enterprise Repository
Oracle Enterprise RepositoryPrabhat 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 JMHAndres 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 ServicesHaytham Ghandour
 
06 Using More Package Concepts
06 Using More Package Concepts06 Using More Package Concepts
06 Using More Package Conceptsrehaniltifat
 
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.0Haytham Ghandour
 
EMC Documentum - xCP.x Updating Endpoint
EMC Documentum - xCP.x Updating EndpointEMC Documentum - xCP.x Updating Endpoint
EMC Documentum - xCP.x Updating EndpointHaytham Ghandour
 
Polymorphic Table Functions in SQL
Polymorphic Table Functions in SQLPolymorphic Table Functions in SQL
Polymorphic Table Functions in SQLChris Saxon
 
1 z0 060 - oracle certification
1 z0 060 - oracle certification1 z0 060 - oracle certification
1 z0 060 - oracle certificationadam_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 Meschbergermfrancis
 
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
 

Mais procurados (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
 

Semelhante a Тестирование 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 EngineInphina Technologies
 
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 EngineIndicThreads
 
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 2018Ortus 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 ContextGlobalLogic Ukraine
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_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 2012Chen-Tien Tsai
 
Apache Aries Blog Sample
Apache Aries Blog SampleApache Aries Blog Sample
Apache Aries Blog SampleSkills Matter
 
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 PluginsStephen Willcock
 
Data Seeding via Parameterized API Requests
Data Seeding via Parameterized API RequestsData Seeding via Parameterized API Requests
Data Seeding via Parameterized API RequestsRapidValue
 
Spring Cloud Function — Going Serverless
Spring Cloud Function — Going ServerlessSpring Cloud Function — Going Serverless
Spring Cloud Function — Going ServerlessGlobalLogic Ukraine
 
Robustness testing
Robustness testingRobustness testing
Robustness testingCS, NcState
 
Spring Cloud Data Flow Overview
Spring Cloud Data Flow OverviewSpring Cloud Data Flow Overview
Spring Cloud Data Flow OverviewVMware 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 KotlinRapidValue
 
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 AppsVijayan Srinivasan
 

Semelhante a Тестирование 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
 

Mais de 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 groovyVitebsk Miniq
 
The 5 Laws of Software Estimates
The 5 Laws of Software EstimatesThe 5 Laws of Software Estimates
The 5 Laws of Software EstimatesVitebsk Miniq
 
Latest & Greatest Observability Release 7.9
Latest & Greatest Observability Release 7.9Latest & Greatest Observability Release 7.9
Latest & Greatest Observability Release 7.9Vitebsk Miniq
 
Семантический поиск - что это, как работает и чем отличается от просто поиска
Семантический поиск - что это, как работает и чем отличается от просто поискаСемантический поиск - что это, как работает и чем отличается от просто поиска
Семантический поиск - что это, как работает и чем отличается от просто поискаVitebsk Miniq
 
Локализационное тестирование - это не только перевод
Локализационное тестирование - это не только переводЛокализационное тестирование - это не только перевод
Локализационное тестирование - это не только переводVitebsk Miniq
 
ISTQB Сертификация тестировщиков: быть или не быть?
ISTQB Сертификация тестировщиков: быть или не быть?ISTQB Сертификация тестировщиков: быть или не быть?
ISTQB Сертификация тестировщиков: быть или не быть?Vitebsk Miniq
 
Apollo GraphQL Federation
Apollo GraphQL FederationApollo GraphQL Federation
Apollo GraphQL FederationVitebsk Miniq
 
Who is a functional tester
Who is a functional testerWho is a functional tester
Who is a functional testerVitebsk Miniq
 
Вперед в прошлое
Вперед в прошлоеВперед в прошлое
Вперед в прошлоеVitebsk Miniq
 
CloudFormation experience
CloudFormation experienceCloudFormation experience
CloudFormation experienceVitebsk Miniq
 
Learning Intelligence: the story of mine
Learning Intelligence: the story of mineLearning Intelligence: the story of mine
Learning Intelligence: the story of mineVitebsk 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
 

Mais de 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. Практика
 
Разделяй и властвуй!
Разделяй и властвуй!Разделяй и властвуй!
Разделяй и властвуй!
 

Último

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 

Último (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 

Тестирование 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