ConfigDataApplicationContextInitializer
ConfigDataApplicationContextInitializer
es un ApplicationContextInitializer
que se puede
aplicar a pruebas para cargar archivos application.properties
para Spring Boot. Puede usarlo si no
necesita el conjunto completo de funciones proporcionadas por la anotación @SpringBootTest
, como se
muestra en el siguiente ejemplo:
importar org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
importar org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(clases = Config.class, inicializadores = ConfigDataApplicationContextInitializer.class)
clase MyConfigFileTest {
//...
}
importar org.springframework.boot.test.context.ConfigDataApplicationContextInitializer
importar org.springframework.test.context.ContextConfiguration
@ContextConfiguration(clases = [Config::class], inicializadores = [ConfigDataApplicationContextInitializer::class])
clase MyConfigFileTest {
//...
}
ConfigDataApplicationContextInitializer
no brindará soporte para incrustar el @Value("${...}" )
anotación. Su único trabajo es garantizar que los archivos application.properties
se
carguen en el Environment
de Spring. Para admitir la anotación @Value
, debe configurar
adicionalmente la anotación PropertySourcesPlaceholderConfigurer
o usar la anotación @SpringBootTest
,
que la configurará automáticamente. .
PruebaValoresPropiedad
La clase TestPropertyValues
le permite agregar rápidamente propiedades a un ConfigurableEnvironment
o ConfigurableApplicationContext
. Puedes llamarlo usando las líneas key=value
, como se
muestra a continuación:
import org.junit.jupiter.api.Test;
importar org.springframework.boot.test.util.TestPropertyValues;
importar org.springframework.mock.env.MockEnvironment;
importar estática org.assertj.core.api.Assertions.assertThat;
clase MyEnvironmentTests {
@Prueba
anular testPropertySources() {
Entorno MockEnvironment = nuevo MockEnvironment();
TestPropertyValues.of("org=Spring", "nombre=Boot").applyTo(entorno);
afirmarQue(environment.getProperty("nombre")).isEqualTo("Arranque");
}
}
importar org.assertj.core.api.Assertions.assertThat
importar org.junit.jupiter.api.Test
importar org.springframework.boot.test.util.TestPropertyValues
importar org.springframework.mock.env.MockEnvironment
clase MyEnvironmentTests {
@Prueba
divertido testPropertySources() {
entorno val = entorno simulado()
TestPropertyValues.of("org=Spring", "nombre=Boot").applyTo(entorno)
afirmarQue(environment.getProperty("nombre")).isEqualTo("Arranque")
}
}
Captura de salida
OutputCapture
es una Extensión
para JUnit que se puede utilizar para capturar la salida de
System.out
y System.err
. Para usarlo, agregue la anotación @ExtendWith(OutputCaptureExtension.class)
e inyecte CapturedOutput
como argumento en el constructor de su clase de prueba o método de prueba
como este:
import org.junit.jupiter.api.Test;
importar org.junit.jupiter.api.extension.ExtendWith;
importar org.springframework.boot.test.system.CapturedOutput;
importar org.springframework.boot.test.system.OutputCaptureExtension;
importar estática org.assertj.core.api.Assertions.assertThat;
@ExtendWith(OutputCaptureExtension.class)
clase MyOutputCaptureTests {
@Prueba
void testName (salida CapturedOutput) {
System.out.println("¡Hola mundo!");
afirmarque(salida).contiene("Mundo");
}
}
importar org.assertj.core.api.Assertions.assertThat
importar org.junit.jupiter.api.Test
importar org.junit.jupiter.api.extension.ExtendWith
importar org.springframework.boot.test.system.CapturedOutput
importar org.springframework.boot.test.system.OutputCaptureExtension
@ExtendWith(OutputCaptureExtension::clase)
clase MyOutputCaptureTests {
@Prueba
nombre de prueba divertido (salida: ¿Salida capturada?) {
println("¡Hola mundo!")
afirmar que (salida). contiene ("Mundo")
}
}
PlantillaTestRest
TestRestTemplate
es una alternativa conveniente al RestTemplate
de Spring que es útil para
pruebas de integración. Puede obtener una plantilla básica o una que envíe autenticación HTTP básica (con nombre de
usuario y contraseña). En cualquier caso, la plantilla es tolerante a fallos. Esto significa que su lógica operativa
es conveniente para realizar pruebas y no genera excepciones para los errores 4xx y 5xx. En cambio, dichos errores
se pueden detectar a través del ResponseEntity
devuelto y su código de estado.
WebTestClient
que también
es bueno para pruebas de integración en
WebFlux y para pruebas de un
extremo a otro en WebFlux y MVC. A diferencia de TestRestTemplate
, proporciona una API fluida
para
agregar aserciones.
Se recomienda, aunque no es obligatorio, utilizar el cliente HTTP Apache (versión 4.3.2 o superior). Si está en su
classpath, la plantilla TestRestTemplate
responderá a esto y configurará el cliente en consecuencia. Si
está utilizando el cliente HTTP Apache, se agregan algunas características adicionales que son útiles para realizar
pruebas:
-
No se realiza un seguimiento de los redireccionamientos (por lo que puede agregar reclamos para la ubicación de respuesta).
-
Las cookies se ignoran (por lo que la plantilla no guarda el estado).
Se puede crear una instancia de TestRestTemplate
directamente en las pruebas de integración, como se
muestra en el siguiente ejemplo:
import org.junit.jupiter.api.Test;
importar org.springframework.boot.test.web.client.TestRestTemplate;
importar org.springframework.http.ResponseEntity;
importar estática org.assertj.core.api.Assertions.assertThat;
clase MisPruebas {
plantilla TestRestTemplate final privada = new TestRestTemplate();
@Prueba
solicitud de prueba nula() {
ResponseEntity<String> encabezados = this.template.getForEntity("https://myhost.example.com/example", String.class);
afirmarQue(headers.getHeaders().getLocation()).hasHost("otro.ejemplo.com");
}
}
importar org.assertj.core.api.Assertions.assertThat
importar org.junit.jupiter.api.Test
importar org.springframework.boot.test.web.client.TestRestTemplate
clase MisPruebas {
plantilla de valor privado = TestRestTemplate()
@Prueba
divertida pruebaRequest() {
encabezados val = template.getForEntity("https://myhost.example.com/example", String::class.java)
afirmarQue(encabezados.encabezados.ubicación).hasHost("otro.ejemplo.com")
}
}
Además, si usa la anotación @SpringBootTest
con WebEnvironment.RANDOM_PORT
o WebEnvironment.DEFINED_PORT
,
puede inyectar un completamente configurado TestRestTemplate
y comienza a usarlo. Si es necesario,
se pueden aplicar configuraciones adicionales a través del bean RestTemplateBuilder
. Cualquier URL que
no especifique un host y un puerto se conecta automáticamente al servidor integrado, como se muestra en el siguiente
ejemplo:
import java.time.Duration;
importar org.junit.jupiter.api.Test;
importar org.springframework.beans.factory.annotation.Autowired;
importar org.springframework.boot.test.context.SpringBootTest;
importar org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
importar org.springframework.boot.test.context.TestConfiguration;
importar org.springframework.boot.test.web.client.TestRestTemplate;
importar org.springframework.boot.web.client.RestTemplateBuilder;
importar org.springframework.context.annotation.Bean;
importar org.springframework.http.HttpHeaders;
importar estática org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
clase MySpringBootTest {
@autocableado
plantilla TestRestTemplate privada;
@Prueba
solicitud de prueba nula() {
Encabezados HttpHeaders = this.template.getForEntity("/ejemplo", String.class).getHeaders();
afirmarQue(headers.getLocation()).hasHost("otro.ejemplo.com");
}
@TestConfiguration(proxyBeanMethods = falso)
clase estática RestTemplateBuilderConfiguration {
@Frijol
RestTemplateBuilder restTemplateBuilder() {
devolver nuevo RestTemplateBuilder().setConnectTimeout(Duration.ofSeconds(1))
.setReadTimeout(Duración.deSeconds(1));
}
}
}
importar org.assertj.core.api.Assertions.assertThat
importar org.junit.jupiter.api.Test
importar org.springframework.beans.factory.annotation.Autowired
importar org.springframework.boot.test.context.SpringBootTest
importar org.springframework.boot.test.context.SpringBootTest.WebEnvironment
importar org.springframework.boot.test.context.TestConfiguration
importar org.springframework.boot.test.web.client.TestRestTemplate
importar org.springframework.boot.web.client.RestTemplateBuilder
importar org.springframework.context.annotation.Bean
importar java.time.Duración
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
clase MySpringBootTests(@plantilla de valor Autowired: TestRestTemplate) {
@Prueba
divertida pruebaRequest() {
encabezados val = template.getForEntity("/ejemplo", String::class.java).headers
afirmarQue(encabezados.ubicación).hasHost("otro.ejemplo.com")
}
@TestConfiguration(proxyBeanMethods = falso)
clase interna RestTemplateBuilderConfiguration {
@Frijol
divertido restTemplateBuilder(): RestTemplateBuilder {
devolver RestTemplateBuilder().setConnectTimeout(Duración.deSeconds(1))
.setReadTimeout(Duración.deSeconds(1))
}
}
}