0Pricing
Spring Boot 4 Microservices & REST APIs · Lezione

Test di integrazione con @SpringBootTest

Testi l'intero contesto dell'applicazione.

Test di integrazione con @SpringBootTest è una lezione Spring Boot 4 Microservices & REST APIs gratuita su CoddyKit. Questa è la lezione 3 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Spring Boot 4 Microservices & REST APIs, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Spring Boot 4 Microservices & REST APIs include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

What is an Integration Test

An integration test exercises multiple layers together — controller, service, repository — using a real Spring context.

It catches wiring and configuration problems that unit tests miss.

@SpringBootTest

@SpringBootTest boots the entire application context, loading all beans.

@SpringBootTest
class ApplicationIntegrationTest {
    @Autowired
    UserService userService;

    @Test
    void contextLoads() {
        assertThat(userService).isNotNull();
    }
}

WebEnvironment Modes

Control whether a real server starts with the webEnvironment attribute.

  • MOCK (default) — mock servlet environment
  • RANDOM_PORT — real server on a random port
@SpringBootTest(
    webEnvironment = WebEnvironment.RANDOM_PORT)
class ApiTest { }

Testing with TestRestTemplate

With a real port you can make actual HTTP calls using TestRestTemplate.

@Autowired
TestRestTemplate restTemplate;

@Test
void getsUser() {
    ResponseEntity<User> response =
        restTemplate.getForEntity("/users/1", User.class);
    assertThat(response.getStatusCode())
        .isEqualTo(HttpStatus.OK);
}

WebTestClient

WebTestClient is a fluent client that works for both MVC and WebFlux apps.

@Autowired
WebTestClient webTestClient;

@Test
void getsUser() {
    webTestClient.get().uri("/users/1")
        .exchange()
        .expectStatus().isOk()
        .expectBody()
        .jsonPath("$.name").isEqualTo("Alice");
}

Using a Test Database

By default Spring Boot can replace your datasource with an in-memory H2 database for tests.

@SpringBootTest
@AutoConfigureTestDatabase
class RepositoryIntegrationTest {
    @Autowired UserRepository repository;
}

Test Properties

Override configuration for tests with @TestPropertySource or an application-test.properties profile.

@SpringBootTest
@TestPropertySource(properties = {
    "feature.enabled=false"
})
class FeatureTest { }

Activating Profiles

Use @ActiveProfiles to run with a specific Spring profile.

@SpringBootTest
@ActiveProfiles("test")
class ServiceTest { }

Transactional Rollback

Annotate tests with @Transactional so each test's database changes roll back automatically, keeping tests isolated.

@SpringBootTest
@Transactional
class UserPersistenceTest {
    @Test
    void savesAndRollsBack() {
        repository.save(new User("Alice"));
    }
}

Slicing for Speed

Full @SpringBootTest is slow. Prefer slices like @DataJpaTest or @WebMvcTest when you only need one layer.

@DataJpaTest

@DataJpaTest loads only JPA components and an embedded database — ideal for repository tests.

@DataJpaTest
class UserRepositoryTest {
    @Autowired UserRepository repository;

    @Test
    void findsByName() {
        repository.save(new User("Alice"));
        assertThat(repository.findByName("Alice"))
            .hasSize(1);
    }
}

Quick Check

Test your understanding of integration testing.

Recap

You learned to write integration tests:

  • @SpringBootTest loads the full context
  • RANDOM_PORT + TestRestTemplate/WebTestClient for real HTTP
  • @Transactional rolls back DB changes
  • Use slices for speed

Domande Frequenti

La lezione «Test di integrazione con @SpringBootTest» è gratuita?

Sì — il testo completo di «Test di integrazione con @SpringBootTest» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Spring Boot 4 Microservices & REST APIs, passa a CoddyKit PRO. Il corso Spring Boot 4 Microservices & REST APIs include 4 lezioni in totale.

Cosa imparerò in «Test di integrazione con @SpringBootTest»?

Testi l'intero contesto dell'applicazione. Eserciti Spring Boot 4 Microservices & REST APIs con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Spring Boot 4 Microservices & REST APIs?

Non è richiesta alcuna esperienza precedente. Spring Boot 4 Microservices & REST APIs su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 4.

Quanto tempo richiede la lezione «Test di integrazione con @SpringBootTest»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Spring Boot 4 Microservices & REST APIs?

Sì. Ogni lezione Spring Boot 4 Microservices & REST APIs include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Test unitari con JUnit e Mockito
  2. Test del web layer con MockMvc
  3. Test di integrazione con @SpringBootTest
  4. Dipendenze reali con Testcontainers
← Torna a Spring Boot 4 Microservices & REST APIs