When I first shared my list of
20+ Spring Boot Interview Questions, I got a lot of emails to add more interview questions, particularly from
Testing and Spring Boot testing topics where I have seen a lot of interest
from the interviewers. So, I decided to write a separate article
containing spring boot testing interview questions.
Since there is a lot of overlap, I have combined all spring boot testing questions in one article. This article contains all the answers to Testing and Spring Boot Testing questions from the Spring certification guide as well as some common Spring boot questions.
1. How to define a testing class in Spring?
Here are the steps needed to define a testing class in Spring application:
2. Which starter package do you need to test the spring boot application?
To unit test the Spring Boot application you will need to use the spring-boot-starter-test, which imports both Spring Boot test modules as well as JUnit Jupiter, AssertJ, Hamcrest, and a number of other useful libraries.
4. What are the three common Spring boot test annotations are?
Three common Spring boot test annotations are @DataJpaTest, @WebMvcTest, and @SpringBootTest which can be used to test Spring Data JPA repository, Spring MVC application, and Spring Boot, classes.
Spring Boot provides a @SpringBootTest annotation, which can be used as an alternative to the standard spring-test @ContextConfiguration annotation when you need Spring Boot features.
Spring Boot also provides @MockBean annotation that can be used to define a Mockito mock for a bean inside our ApplicationContext, which means the mock declared in test class (by using @MockBean) will be injected as a bean within the application.
5. How can you create a shared application context in a JUnit integration test?
You can create a shared application context in a JUnit integration test by implementing the ApplicationContextAware interface as shown in the following example:
6. When and where do you use @Transactional in testing?
If you remember, the @Transactional annotation defines the scope of a single database transaction and a database transaction happens inside the scope of a persistence context. On testing, you can use @Transaction annotation at both methods and class levels.
At the method level, the annotated test method(s) will run, each in its own transaction. By default, automatically rolled back after completion of the test. You can also alter this behavior by disabling the defaultRollback attribute of @TransactionConfiguration.
You can also use @Transactional at the class level and in that case, each test method within that class hierarchy runs within a transaction.
7. How is @ContextConfiguration used in Spring Boot?
The @ContextConfiguration is an important annotation for Spring Boot testing. It is a class-level annotation that is used to load the application context for the integration test. This is defined in the spring-test module.
Here is an example of @ContextConfiguration in Spring Boot tests
This example, it uses BookConfiguration class to create an application context and load bean definitions. if @ContextConfiguration is used without any attributes defined, the default behavior of spring boot is to search for a file named {testClassName}-context.xml in the same location as the test class and load bean definitions from there if found.
Spring Boot also provides @SpringBootTest annotation, which can be used as an alternative to the standard spring-test @ContextConfiguration annotation when you need Spring Boot features.
16. What are the differences between @MockBean and @Mock annotations?
Both @Mock and @MockBean are used extensively while writing unit tests in Java and Spring applications. You should use @Mock when unit testing your business logic independent of the Spring framework.
17. When do you want @DataJpaTest for? What does it auto-configure?
You can use @DataJpaTest annotation to set up an environment with an embedded database to test your database queries against. This is one of the convenient features Spring boot provides to simplify testing.
18. What is the use of @DirtiesContext annotation while Testing Spring Boot application?
One of the nice features of Spring Test support is that the application context is cached between tests. That way, if you have multiple methods in a test case or multiple test cases with the same configuration, they incur the cost of starting the application only once. You can control the cache by using the @DirtiesContext annotation.
19. What is the difference between @ContextConfiguration and @SpringApplicatoinConfiguration in Spring Boot testing?
While both @ContextConfiguration and @SpringApplicatoinConfiguration annotations can be used to load application context for spring boot testing, there is a subtle difference between them.
This class not only loads the application context but also enables logging and loading of external properties specified in the application.properties or application.yml file, and other features of the Spring Boot framework, which is not loaded or enabled by the @ContextConfiguration annotation.
In short, it's better to use the @SpringApplicatoinConfiguration annotations rather than @ContextConfiguration for writing an integration test for the Spring boot application.
20. What is the difference between @ContextConfiguration and @SpringBootTest?
This question is also very similar to the previous question. Unlike the @ContextConfiguration which just loads spring beans and creates application context for testing without using spring boot features, the @SpringBootTest annotation uses SpringApplication behind the scenes to load ApplicationContext so that all the Spring Boot features will be available.
21. Can you name common annotations used for testing a Spring Boot application?
That's all about Spring Boot Testing Interview Questions and Answers for Java developers. This article not only covers spring boot-specific testing questions but also general Spring framework testing questions. It also answers all the testing-related questions that you will find in the official Spring Certification Exam guide, hence if you are preparing for spring certification, you can also refer to these answers to improve your knowledge about this important topic.
Thanks for reading this article so far. If you find these
best Spring and Spring Boot Testing interview questions useful then please share them with your friends and colleagues.
If you have any questions or feedback then please drop a note.
At that time, many Java developers also asked me to provide answers for
Spring and Spring boot testing questions given on the official Spring
Certification guide which is also a great resource for anyone preparing for
Spring certification
and
Spring boot interviews.
Since there is a lot of overlap, I have combined all spring boot testing questions in one article. This article contains all the answers to Testing and Spring Boot Testing questions from the Spring certification guide as well as some common Spring boot questions.
While many of them are already popular on Spring boot interviews they will
also help you to learn Spring boot better and pass the spring certification,
if you are aiming to become a certified Spring Developer.
By the way, if you want to learn Spring Boot testing in-depth, I also
recommend joining a comprehensive testing course like Testing Spring Boot: Beginner to Guru by John Thompson to learn essential Spring Boot testing
concepts.
Without any further ado, here is the list of frequently asked Spring and Spring Boot testing interview questions with answers:
31 Spring Framework and Spring Boot Testing Interview Questions Answers
If you have worked on Spring projects then you know that we can use JUnit to test a Spring application and this article will show more lights on how to use Spring Test and Spring Boot features to test the interactions between Spring and your code through popular interview questions.Without any further ado, here is the list of frequently asked Spring and Spring Boot testing interview questions with answers:
1. How to define a testing class in Spring?
Here are the steps needed to define a testing class in Spring application:
- annotate the test class with @RunWith(SpringJUnit4ClassRunner.class)
- annotate the class with @ContextConfiguration or @SpringBootTest in order to tell the runner class where the bean definitions come from
- use @Autowired to inject beans to be tested.
2. Which starter package do you need to test the spring boot application?
To unit test the Spring Boot application you will need to use the spring-boot-starter-test, which imports both Spring Boot test modules as well as JUnit Jupiter, AssertJ, Hamcrest, and a number of other useful libraries.
The spring-boot-starter-test uses
spring-boot-test and
spring-boot-test-autoconfigure.
You can further see Testing Spring Boot: Beginner to Guru for some live examples of writing tests using the spring MVC test and which
starter packages are automatically imported and which testing libraries they
automatically configure.
3. What type of tests typically use Spring?
Spring framework provides excellent support for testing, you can write both unit tests and integration tests using Spring and Spring Boot.
3. What type of tests typically use Spring?
Spring framework provides excellent support for testing, you can write both unit tests and integration tests using Spring and Spring Boot.
A unit test
is used to test individual classes like
controllers
while an integration test can be used to test the interaction of multiple
units working together.
Spring also provides mock objects for unit testing
and also provide excellent support for integration tests on the
spring-test module.
4. What are the three common Spring boot test annotations are?
Three common Spring boot test annotations are @DataJpaTest, @WebMvcTest, and @SpringBootTest which can be used to test Spring Data JPA repository, Spring MVC application, and Spring Boot, classes.
Spring Boot provides a @SpringBootTest annotation, which can be used as an alternative to the standard spring-test @ContextConfiguration annotation when you need Spring Boot features.
Spring Boot also provides @MockBean annotation that can be used to define a Mockito mock for a bean inside our ApplicationContext, which means the mock declared in test class (by using @MockBean) will be injected as a bean within the application.
If you want to learn more about these annotations as well as some other
sliced context annotations and how to test spring boot applications in
general, I also suggest you check out the
Spring Boot Testing Masterclass
by Philip, a senior Java engineer, and fellow blogger and Youtuber.
Some of his lessons are also free which I think every Java developer should
go through.
5. How can you create a shared application context in a JUnit integration test?
You can create a shared application context in a JUnit integration test by implementing the ApplicationContextAware interface as shown in the following example:
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = BookConfiguration.class)
public class BookBorrowServiceJUnit4ContextTests implements ApplicationContextAware {
//some code to test
}
6. When and where do you use @Transactional in testing?
If you remember, the @Transactional annotation defines the scope of a single database transaction and a database transaction happens inside the scope of a persistence context. On testing, you can use @Transaction annotation at both methods and class levels.
At the method level, the annotated test method(s) will run, each in its own transaction. By default, automatically rolled back after completion of the test. You can also alter this behavior by disabling the defaultRollback attribute of @TransactionConfiguration.
You can also use @Transactional at the class level and in that case, each test method within that class hierarchy runs within a transaction.
You can also override this class-level rollback behavior at the method
level using the
@Rollback annotation, which
requires a boolean value,
@Rollback(false).
By the way, if you want to learn more about the
@Transaction annotation in
Spring then you can also see the
Spring Framework for Beginners with Spring Boot
course on Udemy to learn more about how and when to use
@Transactional annotation in
Spring Framework.
7. How is @ContextConfiguration used in Spring Boot?
The @ContextConfiguration is an important annotation for Spring Boot testing. It is a class-level annotation that is used to load the application context for the integration test. This is defined in the spring-test module.
Here is an example of @ContextConfiguration in Spring Boot tests
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=BookConfiguration.class)
public class BookServiceTest {
@Autowired
private BookService bookService;
@Test public void testBookService() {
Book aBook = bookService.findByTitle("Spring Boot in Action");
assertEquals("Craig Walls", aBook.getAuthor());
assertEquals(40, aBook.getPrice());
}
}
This example, it uses BookConfiguration class to create an application context and load bean definitions. if @ContextConfiguration is used without any attributes defined, the default behavior of spring boot is to search for a file named {testClassName}-context.xml in the same location as the test class and load bean definitions from there if found.
Spring Boot also provides @SpringBootTest annotation, which can be used as an alternative to the standard spring-test @ContextConfiguration annotation when you need Spring Boot features.
The annotation works by creating the
ApplicationContext used in your
tests through SpringApplication which not only loads the application
context but also enables logging and loading of external properties
specified in the
application.properties or
application.yml file, and other features of the Spring Boot framework,
which is not loaded or enabled by the
@ContextConfiguration
annotation.
If you want to master JUnit and Mockito, which you should and need
resources then also suggest you checkout Learn Java Unit Testing with Junit & Mockito in 30 Steps
course by Ranga Karnam of In28Minutes on Udemy.
8. How are mock frameworks such as Mockito or EasyMock used in Spring
Boot?
You can use both Mockito and mock object frameworks like EasyMock to write tests in Spring Boot. Mockito allows you to write tests by mocking the external dependencies with the desired behavior while Mock objects can be used to test specific scenarios.
You can use Mockito in the Spring boot application using either by @RunWith(MockitoJUnitRunner.class) to initialize the mock objects or by using MockitoAnnotations.initMocks(this) in the JUnit @Before method.
You can also use @MockBean annotation provided by Spring Boot which can be used to define a new Mockito mock bean or replace a Spring bean with a mock bean and inject that into their dependent beans. Another good thing about this is that If your test uses one of Spring Boot’s test annotations (such as @SpringBootTest), this feature is automatically enabled.
9. How does Spring Boot simplify writing tests?
Spring boot provides a starter dependency spring-boot-starter-test which loads all-important testing libraries.
You can use both Mockito and mock object frameworks like EasyMock to write tests in Spring Boot. Mockito allows you to write tests by mocking the external dependencies with the desired behavior while Mock objects can be used to test specific scenarios.
You can use Mockito in the Spring boot application using either by @RunWith(MockitoJUnitRunner.class) to initialize the mock objects or by using MockitoAnnotations.initMocks(this) in the JUnit @Before method.
You can also use @MockBean annotation provided by Spring Boot which can be used to define a new Mockito mock bean or replace a Spring bean with a mock bean and inject that into their dependent beans. Another good thing about this is that If your test uses one of Spring Boot’s test annotations (such as @SpringBootTest), this feature is automatically enabled.
9. How does Spring Boot simplify writing tests?
Spring boot provides a starter dependency spring-boot-starter-test which loads all-important testing libraries.
For example, the following libraries will be loaded within the test
scope:
Spring Boot also provides a @SpringBootTest annotation, which can be used as an alternative to the standard spring-test @ContextConfiguration annotation when you need Spring Boot features.
10. What does @SpringBootTest do? How does it interact with @SpringBootApplication and @SpringBootConfiguration?
The @SpringBootTest annotation tells Spring Boot to look for the main configuration class (the one with @SpringBootApplication, for instance) and use that to start a Spring application context.
11. When do you want to use @SpringBootTest annotation?
You can use @SpringBootTest annotation whenever you want to test your Spring boot application. For example, you can use @SpringBootTest to verify if the context is loaded or not and if the context is creating your controller or not.
here is an example of using @SpringBootTest annotation to check
You can see we are verifying if the controller is created or not using AssertJ methods.
12. What does @SpringBootTest auto-configure?
Spring Boot provides the @SpringBootTest annotation, which can be used as an alternative to the standard spring-test @ContextConfiguration annotation when you need Spring Boot features.
- JUnit: standard library for writing unit tests in Java
- JSON Path: XPath for JSON
- AssertJ: Fluent assertion library
- Mockito: Java mocking library
- Hamcrest: Library of matcher objects
- JSONassert: Assertion library for JSON
- Spring Test and Spring Boot Test: These are the test libraries provided by the Spring Framework and Spring Boot.
Spring Boot also provides a @SpringBootTest annotation, which can be used as an alternative to the standard spring-test @ContextConfiguration annotation when you need Spring Boot features.
10. What does @SpringBootTest do? How does it interact with @SpringBootApplication and @SpringBootConfiguration?
The @SpringBootTest annotation tells Spring Boot to look for the main configuration class (the one with @SpringBootApplication, for instance) and use that to start a Spring application context.
11. When do you want to use @SpringBootTest annotation?
You can use @SpringBootTest annotation whenever you want to test your Spring boot application. For example, you can use @SpringBootTest to verify if the context is loaded or not and if the context is creating your controller or not.
here is an example of using @SpringBootTest annotation to check
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class CheckControllerTest {
@Autowired
private BookController controller;
@Test
public void contextLoads() throws Exception {
assertThat(controller).isNotNull();
}
}
You can see we are verifying if the controller is created or not using AssertJ methods.
12. What does @SpringBootTest auto-configure?
Spring Boot provides the @SpringBootTest annotation, which can be used as an alternative to the standard spring-test @ContextConfiguration annotation when you need Spring Boot features.
The annotation works by
creating the
ApplicationContext used in your
tests through SpringApplication just like
@SpringApplicaitonConfiguration
does.
13. What dependencies does the spring-boot-starter-test brings to the classpath?
The spring-boot-starter-test adds the following useful testing libraries into classpath:
14. How do you perform integration testing with @SpringBootTest for a web application?
You can either use @SpringBootTest to load full context for integration test or you can use @WebMvcTest to only load the web layer interested in loading the whole context.
15. When do you want to use @WebMvcTest? What does it auto-configure?
You can use @WebMvcTest annotation for testing the web layer of your Spring Boot application. When you use @WebMvcTest instead of @SpringBootTest then Spring Boot only instantiates the web layer rather than the whole context.
13. What dependencies does the spring-boot-starter-test brings to the classpath?
The spring-boot-starter-test adds the following useful testing libraries into classpath:
- JUnit 4: The de-facto standard for unit testing Java applications.
- Spring Test & Spring Boot Test: Utilities and integration test support for Spring Boot applications.
- AssertJ: A fluent assertion library.
- Hamcrest: A library of matcher objects (also known as constraints or predicates).
- Mockito: A Java mocking framework.
- JSONassert: An assertion library for JSON.
- JsonPath: XPath for JSON.
14. How do you perform integration testing with @SpringBootTest for a web application?
You can either use @SpringBootTest to load full context for integration test or you can use @WebMvcTest to only load the web layer interested in loading the whole context.
15. When do you want to use @WebMvcTest? What does it auto-configure?
You can use @WebMvcTest annotation for testing the web layer of your Spring Boot application. When you use @WebMvcTest instead of @SpringBootTest then Spring Boot only instantiates the web layer rather than the whole context.
If your Spring Boot application has multiple controllers then you can even
instantiate a particular controller by specifying it as a parameter, for
example,
@WebMvcTest(BookController.class)
will only instantiate
BookController in your web
layer.
16. What are the differences between @MockBean and @Mock annotations?
Both @Mock and @MockBean are used extensively while writing unit tests in Java and Spring applications. You should use @Mock when unit testing your business logic independent of the Spring framework.
You can do this by
using only using JUnit and Mockito and use
@MockBean when you write a test
that is backed by a Spring Test Contexts and you want to add or replace a
bean with a mocked version of it.
If you need resource, Testing Spring Boot App with JUnit, Mockito & Testcontainers course by Ramesh Fadatare of JavaGuides is a great course to start with.
17. When do you want @DataJpaTest for? What does it auto-configure?
You can use @DataJpaTest annotation to set up an environment with an embedded database to test your database queries against. This is one of the convenient features Spring boot provides to simplify testing.
You can use @DataJpaTest to
test Spring Data JPA repositories or any other JPA-related components. All
you need to do is just add it you our unit test and it will set up a
Spring application context:
Here is an example of @DataJpaTest annotation in the Spring Boot application:
Btw, these code examples use the @ExtendWith annotation to tell JUnit 5 to enable Spring support. but from Spring Boot 2.1, you don't need to load the SpringExtension because it's automatically included as a meta-annotation in the Spring Boot test annotations like @DataJpaTest, @WebMvcTest, and @SpringBootTest.
Here is an example of @DataJpaTest annotation in the Spring Boot application:
@ExtendWith(SpringExtension.class)
@DataJpaTest
public class OrderEntityRepositoryTest {
@Autowired
private DataSource dataSource;
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private EntityManager entityManager;
@Autowired
private OrderRepository orderRepository;
@Test
public void injectedComponentsAreNotNull(){
assertThat(dataSource).isNotNull();
assertThat(jdbcTemplate).isNotNull();
assertThat(entityManager).isNotNull();
assertThat(orderRepository).isNotNull();
}
}
Btw, these code examples use the @ExtendWith annotation to tell JUnit 5 to enable Spring support. but from Spring Boot 2.1, you don't need to load the SpringExtension because it's automatically included as a meta-annotation in the Spring Boot test annotations like @DataJpaTest, @WebMvcTest, and @SpringBootTest.
You can further see Chad Darby's Spring Boot Unit Testing with JUnit, Mockito and MockMvc course on Udemy to learn more about how to use @DataJpaTest, @WebMvcTest,
and @SpringBootTest annotations to test your database layer, web layer, and whole spring
boot application.
18. What is the use of @DirtiesContext annotation while Testing Spring Boot application?
One of the nice features of Spring Test support is that the application context is cached between tests. That way, if you have multiple methods in a test case or multiple test cases with the same configuration, they incur the cost of starting the application only once. You can control the cache by using the @DirtiesContext annotation.
19. What is the difference between @ContextConfiguration and @SpringApplicatoinConfiguration in Spring Boot testing?
While both @ContextConfiguration and @SpringApplicatoinConfiguration annotations can be used to load application context for spring boot testing, there is a subtle difference between them.
While
@ContextConfiguration loads
application context it doesn't take full advantage of useful Spring Boot
features. Spring Boot applications are ultimately loaded by either
SpringApplication (in the case
of the JAR) or
SpringBootServletInitializer
(for web applications).
This class not only loads the application context but also enables logging and loading of external properties specified in the application.properties or application.yml file, and other features of the Spring Boot framework, which is not loaded or enabled by the @ContextConfiguration annotation.
In short, it's better to use the @SpringApplicatoinConfiguration annotations rather than @ContextConfiguration for writing an integration test for the Spring boot application.
20. What is the difference between @ContextConfiguration and @SpringBootTest?
This question is also very similar to the previous question. Unlike the @ContextConfiguration which just loads spring beans and creates application context for testing without using spring boot features, the @SpringBootTest annotation uses SpringApplication behind the scenes to load ApplicationContext so that all the Spring Boot features will be available.
21. Can you name common annotations used for testing a Spring Boot application?
Yeah sure, here are common annotations which I have used for Spring Boot applction:
The bottom two are JUnit annotations but used heavily while Testing Spring Boot application.
That's all about Spring Boot Testing Interview Questions and Answers for Java developers. This article not only covers spring boot-specific testing questions but also general Spring framework testing questions. It also answers all the testing-related questions that you will find in the official Spring Certification Exam guide, hence if you are preparing for spring certification, you can also refer to these answers to improve your knowledge about this important topic.
Other Java and Spring articles you may like
- 15 Spring Data JPA Interview Questions with answers (questions)
- 5 courses to learn Spring Boot and Spring Cloud ( courses)
- 15 Spring Cloud Interview Questions for Java developers (answers)
- 5 Courses to learn Spring Cloud and Microservices (courses)
- 15 Microservices Interview questions (answers)
- 3 Best Practices Java Programmers can learn from Spring (best practices)
- 5 Course to Master Spring Boot online (courses)
- 10 Spring MVC annotations Java developers should learn (annotations)
- 10 Tools Java Developers use in their day-to-day life (tools)
- 10 Courses to learn Spring Security with OAuth 2 (courses)
- Top 5 Books and Courses to learn RESTful Web Service (books)
- 5 Spring Boot Annotations for full-stack Java developers (tutorial)
- 3 ways to change Tomcat port in Spring Boot (tutorial)
- Top 5 Courses to learn Microservices in Java? (courses)
- 10 Advanced Spring Boot Courses for Java Programmers (courses)
P. S. - If you want to learn about Spring Boot and looking for a
free Spring Boot online course then I also recommend you to join
the Introducing Spring Boot (FREE ) course by Dan Vega on Udemy. It's one of the best free
courses to learn Spring Boot for Java developers.
No comments:
Post a Comment