Εμφάνιση αναρτήσεων με ετικέτα @ControllerAdvice. Εμφάνιση όλων των αναρτήσεων
Εμφάνιση αναρτήσεων με ετικέτα @ControllerAdvice. Εμφάνιση όλων των αναρτήσεων

Δευτέρα 2 Δεκεμβρίου 2024

Exception handling with Spring Boot

 EXCEPTION HANDLING WITH SPRING BOOT



1. Use @ResponseStatus for simple cases




When ResourceNotFoundException get thrown, client will get a 404 status code.



2. Use @ControllerAdvice for Centralized Exception Handling



  • @ControllerAdvice handler intercepts exceptions thrown from any controller.
  • With ResponseEntity, we can return custom error messages, objects, HTTP status codes and response bodies.



3. ErrorResponse custom pojo class


     Moreover, we can define an ErrorResponse custom pojo model to include in                         ResponseEntity:






4. Include validation errors in ResponseEntity




    We can stream all errors gathered, into an ErrorResponse's errorMessage string value.




5. Map custom exceptions to error codes for API integrity




In our CustomBusinessException we link a specific Error Code (e.g. ERROR_1)
Then, we add it in ErrorResponse and to ResponseEntity.

That way, clients that consume our API will have a clear matching between our backend errors and an identifying reason (error code)





Σάββατο 23 Οκτωβρίου 2021

Spring Certification: Spring Boot Testing

When do you want to use @SpringBootTest annotation?
  • When we want to load whole ApplicationContext for our tests
  • Mostly when running a JUnit integration test
  • @SpringBootTest will search for a main configuration class or @SpringBootApplication annotated class upwards the project structure tree, and start a Spring application on a mock or running environment, with full application context - no slicing.
  • To use it:
    • JUnit 4 - Add @RunWith(SpringRunner.class) also
    • JUnit 5 - Runner is already included in the annotation

What does @SpringBootTest auto-configure?
  • @SpringBootTest  searches for  @SpringBootApplication / @SpringBootConfiguration, which contains @EnableAutoConfiguration, which triggers Spring AutoConfiguration mechanism.

  • So it uses all xxxAutoConfiguration classes in spring.factories, which autoconfigure all beans needed, according to what exists in the classpath

  • Alternatively, @SpringBootTest(classes = CustomApplication.class) sets a specific main configuration class

  • Also, @SpringBootTest(properties = "spring.main.web-application-type=reactive") takes in account specific properties file



What dependencies does spring-boot-starter-test brings to the classpath?
  • Spring Test
  • Spring Boot Test modules
  • JSONPath
  • JUnit,
  • AssertJ
  • Mockito
  • Hamcrest
  • JSONassert


How do you perform integration testing with @SpringBootTest for a web application?
  • Integration tests should be performed in a full running server environment, so we use:
    • @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) (or defined port)
    • And a fully configured TestRestTemplate or WebTestClient to act a REST client for our tests 
  • Integration tests could be run in a mock servlet environment, that by default @SpringBootTest bootstraps. The original application context will be loaded. For actual test methods, we will use MockMvc. Generally, note that there are no actual mocks of any classes. Also we don't need to use @MockBean or mocks like in @WebMvcTest 




  • Additionally, we might need a test-only property file, so we use @TestPropertySource. As mentioned, the @Value annotations will now be injected from our test property file.



When do you want to use @WebMvcTest? What does it auto-configure?
  • When we want to test the web slice of an application, particularly the behavior of the controllers interacting with the outer world.
  • By default, it autoconfigures all Spring beans referring to the web part, and specifically:
    • @Controller
    • @ControllerAdvice
    • @JsonComponent
    • @WebMvcConfigurer
    • and more
  • Can autoconfigure specific controller with: @WebMvcTest(SomeController.class)
  • Except for @Controllers setup, we must mock their dependencies with use of @MockBean
  • Autoconfigures MockMvc, to use in performing mock web tests



Differences between @SpringBootTest, MockMvc, @WebMvcTest





What are the differences between @MockBean and @Mock?
  • @Mock  is used to create mocks of any class, generally method-wise, while @MockBean to replace Spring bean context-wise
  • @Mock needs @RunWith(MockitoJUnitRunner.class) (Mockito library), while @MockBean needs @RunWith(SpringRunner.class) (spring-boot-test)
  • @Mock creates a Mockito mock, while @MockBean creates a Mockito mock and injects it into the Application Context
  • In order for a @Mock to be injected in its container class, need to use @InjectMocks on container class reference


When do you want @DataJpaTest for? What does it auto-configure?
  • Use for test slicing, particularly for testing of Spring beans that talk to a database (Entities, Repositories)
  • Configures in-memory database for testing
  • Loads in Application Context: @Entities, @Repositories, @TestEntityManager