Spring Boot Testing
Testing - Mock Objects, TestContext Framework, Spring MVC Test, WebTestClient : https://docs.spring.io/spring-framework/docs/current/reference/html/testing.html#testing
Extends with
- Mocktito Runner
- Spring Runner
- Spring Extension When should we use one vs the others?
Integration tests in springboot application with wiremock.
While running the integration test, how to use embedded Kafka, embedd MySQL, embedded gRPC server, etc. using TestContainers while running my integration test suite? https://egkatzioura.com/2020/12/09/testing-using-testcontainers/
@SpringBootTest
See https://github.com/explorer436/programming-playground/tree/main/java-playground/testing-examples
The @SpringBootTest
annotation tells Spring Boot to look for a main configuration class (one with @SpringBootApplication, for instance) and use that to start a Spring application context for testing purposes.
Testing if the context loads correctly
Here is a simple sanity check test that will fail if the application context cannot start.
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class TestingWebApplicationTests {
@Test
public void contextLoads() {
}
}
Testing if the context creates the controller (or any other beans) correctly
If your app has a controller, to test if the context is creating your controller, you could add an assertion:
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 SmokeTest {
@Autowired
private HomeController controller;
@Test
public void contextLoads() throws Exception {
assertThat(controller).isNotNull();
}
}
Spring interprets the @Autowired
annotation, and the controller is injected before the test methods are run.
DirtiesContext annotation
A nice feature of the 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.