Ceci est le 5ème volet de la série «Spring Framework 5.0 Major Changes» et les principaux changements liés à Test (nouvelles fonctionnalités, améliorations, etc.) Je voudrais présenter.
Dans Spring Framework 5.0, les modifications suivantes ont été apportées à la fonction de test.
Numéro d'article | Changements |
---|---|
1 | Spring TestContext Framework(TCF)ÀJUnit 5 JupiterSeradisponiblesur.[Verslesdétails:arrow_right:] Note: SpringExtension classe,@SpringJUnitConfig Annotation,@SpringJUnitWebConfig Annotation,@EnabledIf Annotation,@DisabledIf Une annotation est ajoutée. |
2 | Permet l'exécution parallèle de tests à l'aide de Spring TestContext Framework.[Vers les détails:arrow_right:] |
3 | TestExecutionListener Une méthode de rappel qui est appelée sur l'interface immédiatement avant et après l'exécution du test.(beforeTestExecution QuandafterTestExecution )Sera ajouté.[Vers les détails:arrow_right:] |
4 | MockHttpServletRequest Méthode pour accéder à la requête BODY(getContentAsByteArray QuandgetContentAsString )Sera ajouté.[Vers les détails:arrow_right:] |
5 | MockMvc Lors de la sortie du résultat du test au moment de l'utilisation sur la console ou le journal(MockMvcResultHandlers deprint Oulog Lors de l'utilisation de la méthode)De plus, la requête BODY sera également sortie.[Vers les détails:arrow_right:] |
6 | MockMvc Vous pourrez spécifier un modèle d'URI pour la valeur attendue lors de la vérification de «l'URL de destination de redirection» et de «l'URL de destination de redirection» lors de son utilisation.[Vers les détails:arrow_right:] |
7 | La version prise en charge de XMLUnit, une bibliothèque prenant en charge la validation XML, est 2..Ce sera 3.[Vers les détails:arrow_right:] |
[SPR-13575]: Le point culminant des modifications liées aux tests dans Spring Framework 5.0 est [JUnit 5 Jupiter](http :) //junit.org/junit5/) sur [Spring TestContext Framework (TCF)](http://docs.spring.io/spring/docs/5.0.0.RC1/spring-framework-reference/testing.html# intégration-testing) sera disponible. En particulier···
classe(Annotation) | La description |
---|---|
SpringExtension |
"" Fourni par Junit 5Point d'expansion(Extension )Il s'agit d'une classe qui vous permet d'utiliser le Spring TestContext Framework sur Junit 5.Sur JUnit 4 SpringRunner 、SpringClassRule OuSpringMethodRule Jouez le même rôle. |
@SpringJUnitConfig |
Annotation synthétique pour montrer que Spring TestContext Framework est utilisé sur Junit 5(@ExtendWith(SpringExtension.class) + @ContextConfiguration )est. |
@SpringJUnitWebConfig |
Annotation synthétique pour montrer que Spring TestContext Framework pour l'environnement WEB est utilisé sur Junit 5(@ExtendWith(SpringExtension.class) + @ContextConfiguration + @WebAppConfiguration )est. |
@EnabledIf |
Satisfait aux conditions spécifiées (le résultat de l'expression spécifié par SpEL esttrue C'est une annotation indiquant que le test est exécuté lorsque (devient). |
@DisabledIf |
Satisfait aux conditions spécifiées (le résultat de l'expression spécifié par SpEL esttrue C'est une annotation indiquant que le test est ignoré lorsque (devient). |
Sera ajouté. Les fonctions de TCF lui-même sont les mêmes sur JUnit 4 et JUnit 5, de sorte que l'explication des fonctions TCF est omise dans cette entrée. Seule la méthode de mise à disposition du TCF changera.
Cette entrée n'explique pas fondamentalement Junit 5, mais vous avez besoin d'un environnement pour tester sur Junit 5. Alors ... pour l'instant, créons un projet Maven qui utilise Junit 5 et exécutons un test simple.
Tout d'abord, créez un répertoire arbitraire (exemple: / usr / local / apps / spring5-test-demo
), et créez la structure de répertoire dans ce répertoire comme suit.
$ mkdir -p /usr/local/apps/spring5-test-demo
$ cd /usr/local/apps/spring5-test-demo
...
$ tree
.
└── src
├── main
│ ├── java
│ └── resources
└── test
├── java
└── resources
Ensuite, créez pom.xml.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example.spring5testdemo</groupId>
<artifactId>spring5-test-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<junit-jupiter.version>5.0.0-M4</junit-jupiter.version>
<junit-platform.version>1.0.0-M4</junit-platform.version>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version> <!--Le dernier au moment de la rédaction est 2.Il était 20, mais j'abaisse la version car OutOfMemoryError apparaît lorsque le test échoue ...-->
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit-platform.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
Note: maven-surefire-plugin 2.20 + JUnit 5 avec ʻOutOfMemoryError` sera résolu dans la prochaine version jalon (5.0.0.M5)](https://github.com/junit-team) / junit5 / issues / 809).
Enfin, créez une classe de test.
package com.example.spring5testdemo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class SimpleJunit5Test {
@Test
void simpleTest() {
Assertions.assertEquals("test", "test");
}
}
Vous pouvez également importer ce projet dans un IDE qui prend en charge Junit 5 et utiliser les fonctionnalités de l'EDI pour exécuter des tests sur Junit 5, mais ici nous utilisons le plugin maven-sure fire-plugin. Lançons le test.
$ mvn test
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building spring5-test-demo 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ spring5-test-demo ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ spring5-test-demo ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ spring5-test-demo ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /usr/local/apps/spring5-test-demo/src/test/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ spring5-test-demo ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 1 source file to /usr/local/apps/spring5-test-demo/target/test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.19.1:test (default-test) @ spring5-test-demo ---
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.example.spring5testdemo.SimpleJunit5Test
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec - in com.example.spring5testdemo.SimpleJunit5Test
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.532 s
[INFO] Finished at: 2017-05-20T21:49:02+09:00
[INFO] Final Memory: 17M/300M
[INFO] ------------------------------------------------------------------------
Essayez à nouveau d'exécuter le test pour qu'il échoue.
@Test
void simpleTest() {
Assertions.assertEquals("test", "fail"); //Obtenez toujours une erreur
}
$ mvn test
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building spring5-test-demo 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ spring5-test-demo ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ spring5-test-demo ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ spring5-test-demo ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /usr/local/apps/spring5-test-demo/src/test/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ spring5-test-demo ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 1 source file to /usr/local/apps/spring5-test-demo/target/test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.19.1:test (default-test) @ spring5-test-demo ---
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.example.spring5testdemo.SimpleJunit5Test
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.043 sec <<< FAILURE! - in com.example.spring5testdemo.SimpleJunit5Test
simpleTest() Time elapsed: 0.02 sec <<< FAILURE!
org.opentest4j.AssertionFailedError: expected: <test> but was: <fail>
at com.example.spring5testdemo.SimpleJunit5Test.simpleTest(SimpleJunit5Test.java:10)
Results :
Failed tests:
SimpleJunit5Test.simpleTest:10 expected: <test> but was: <fail>
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.510 s
[INFO] Finished at: 2017-05-20T21:50:21+09:00
[INFO] Final Memory: 17M/257M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.19.1:test (default-test) on project spring5-test-demo: There are test failures.
[ERROR]
[ERROR] Please refer to /usr/local/apps/spring5-test-demo/target/surefire-reports for the individual test results.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
Spring Extension
: point_right:Lors de l'utilisation de Spring TestContext Framework sur JUnit 5, il est nécessaire de spécifier SpringExtension
, mais d'abord, pour pouvoir utiliser Spring Test, pom.xml doit être modifié comme suit.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example.spring5testdemo</groupId>
<artifactId>spring5-test-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<junit-jupiter.version>5.0.0-M4</junit-jupiter.version>
<junit-platform.version>1.0.0-M4</junit-platform.version>
</properties>
<!--★★★ Spring Framework bom(bill of materials)(Gérer le numéro de version côté nomenclature)-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>5.0.0.RC1</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- ★★★ spring-context + spring-Ajouter un test-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<!--★★★ Bibliothèque pour la sortie du journal(logback)Ajouter-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit-platform.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<!--★★★ Ajouter un référentiel Maven contenant respectivement des instantanés Spring et des versions de jalons-->
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone</url>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
</project>
Note:
Si vous n'ajoutez pas la bibliothèque de sortie du journal, vous obtiendrez une erreur lors de l'exécution du test à l'aide de maven-sure fire-plugin. Pourquoi obtenez-vous une erreur? Je ne comprends pas pourquoi l'ajout d'une bibliothèque ne provoque pas d'erreur ... Pour le moment, j'ai répertorié le JIRA de Spring (SPR-15572). À propos, aucune erreur ne s'est produite lors de l'exécution du test avec la fonction IntelliJ. (Pas essayé avec Eclipse / STS)
Après avoir ajouté la bibliothèque, créons en fait une classe de test.
package com.example.spring5testdemo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class) //★★★ Spécifier l'extension de ressort
class SpringTcfOnJunit5Test {
@Autowired private ApplicationContext applicationContext;
@Test
void defaultContextTest() {
Assertions.assertEquals(1, applicationContext.getBeansOfType(MessageSource.class).size());
}
//Fichier de définition de bean en quelque sorte(XML or JavaConfig)Est requis, nous allons donc créer ici une classe JavaConfig en tant que classe interne statique
//Si vous créez une classe JavaConfig en tant que classe interne statique, TCF la détectera automatiquement.
@Configuration
static class LocalTestContext {}
}
Lorsque vous exécutez le test ... le journal suivant est généré et vous pouvez voir que Spring TCF génère ʻApplicationContext` (conteneur DI).
$ mvn test
...
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.example.spring5testdemo.SimpleJunit5Test
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.045 sec - in com.example.spring5testdemo.SimpleJunit5Test
Running com.example.spring5testdemo.SpringTcfOnJunit5Test
00:29:19.216 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
00:29:19.230 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
00:29:19.241 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.example.spring5testdemo.SpringTcfOnJunit5Test] from class [org.springframework.test.context.support.DefaultTestContextBootstrapper]
00:29:19.254 [main] INFO org.springframework.test.context.support.DefaultTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.example.spring5testdemo.SpringTcfOnJunit5Test], using DelegatingSmartContextLoader
00:29:19.258 [main] DEBUG org.springframework.test.context.support.AbstractDelegatingSmartContextLoader - Delegating to GenericXmlContextLoader to process context configuration [ContextConfigurationAttributes@2f0a87b3 declaringClass = 'com.example.spring5testdemo.SpringTcfOnJunit5Test', classes = '{}', locations = '{}', inheritLocations = false, initializers = '{}', inheritInitializers = true, name = [null], contextLoaderClass = 'org.springframework.test.context.ContextLoader'].
00:29:19.261 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.example.spring5testdemo.SpringTcfOnJunit5Test]: class path resource [com/example/spring5testdemo/SpringTcfOnJunit5Test-context.xml] does not exist
00:29:19.261 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.example.spring5testdemo.SpringTcfOnJunit5Test]: no resource found for suffixes {-context.xml}.
00:29:19.262 [main] DEBUG org.springframework.test.context.support.AbstractDelegatingSmartContextLoader - Delegating to AnnotationConfigContextLoader to process context configuration [ContextConfigurationAttributes@2f0a87b3 declaringClass = 'com.example.spring5testdemo.SpringTcfOnJunit5Test', classes = '{}', locations = '{}', inheritLocations = false, initializers = '{}', inheritInitializers = true, name = [null], contextLoaderClass = 'org.springframework.test.context.ContextLoader'].
00:29:19.265 [main] INFO org.springframework.test.context.support.AbstractDelegatingSmartContextLoader - AnnotationConfigContextLoader detected default configuration classes for context configuration [ContextConfigurationAttributes@2f0a87b3 declaringClass = 'com.example.spring5testdemo.SpringTcfOnJunit5Test', classes = '{class com.example.spring5testdemo.SpringTcfOnJunit5Test$LocalTestContext}', locations = '{}', inheritLocations = false, initializers = '{}', inheritInitializers = true, name = [null], contextLoaderClass = 'org.springframework.test.context.ContextLoader'].
00:29:19.276 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.example.spring5testdemo.SpringTcfOnJunit5Test]
00:29:19.278 [main] DEBUG org.springframework.test.context.support.DefaultTestContextBootstrapper - @TestExecutionListeners is not present for class [com.example.spring5testdemo.SpringTcfOnJunit5Test]: using defaults.
00:29:19.279 [main] INFO org.springframework.test.context.support.DefaultTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
00:29:19.286 [main] INFO org.springframework.test.context.support.DefaultTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
00:29:19.287 [main] INFO org.springframework.test.context.support.DefaultTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
00:29:19.287 [main] INFO org.springframework.test.context.support.DefaultTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
00:29:19.288 [main] INFO org.springframework.test.context.support.DefaultTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@d6da883, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@45afc369, org.springframework.test.context.support.DirtiesContextTestExecutionListener@799d4f69]
00:29:19.289 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@69a10787 testClass = SpringTcfOnJunit5Test, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration@2d127a61 testClass = SpringTcfOnJunit5Test, locations = '{}', classes = '{class com.example.spring5testdemo.SpringTcfOnJunit5Test$LocalTestContext}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]], attributes = map[[empty]]], class annotated with @DirtiesContext [false] with mode [null].
00:29:19.290 [main] DEBUG org.springframework.test.context.support.DependencyInjectionTestExecutionListener - Performing dependency injection for test context [[DefaultTestContext@69a10787 testClass = SpringTcfOnJunit5Test, testInstance = com.example.spring5testdemo.SpringTcfOnJunit5Test@11c20519, testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration@2d127a61 testClass = SpringTcfOnJunit5Test, locations = '{}', classes = '{class com.example.spring5testdemo.SpringTcfOnJunit5Test$LocalTestContext}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]], attributes = map[[empty]]]].
00:29:19.290 [main] DEBUG org.springframework.test.context.support.AbstractDelegatingSmartContextLoader - Delegating to AnnotationConfigContextLoader to load context from [MergedContextConfiguration@2d127a61 testClass = SpringTcfOnJunit5Test, locations = '{}', classes = '{class com.example.spring5testdemo.SpringTcfOnJunit5Test$LocalTestContext}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]].
00:29:19.291 [main] DEBUG org.springframework.test.context.support.AbstractGenericContextLoader - Loading ApplicationContext for merged context configuration [[MergedContextConfiguration@2d127a61 testClass = SpringTcfOnJunit5Test, locations = '{}', classes = '{class com.example.spring5testdemo.SpringTcfOnJunit5Test$LocalTestContext}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]].
00:29:19.331 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
00:29:19.332 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
00:29:19.332 [main] DEBUG org.springframework.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
00:29:19.332 [main] DEBUG org.springframework.test.context.support.AnnotationConfigContextLoader - Registering annotated classes: {class com.example.spring5testdemo.SpringTcfOnJunit5Test$LocalTestContext}
00:29:19.362 [main] INFO org.springframework.context.support.GenericApplicationContext - Refreshing org.springframework.context.support.GenericApplicationContext@19dc67c2: startup date [Sun May 21 00:29:19 JST 2017]; root of context hierarchy
00:29:19.362 [main] DEBUG org.springframework.context.support.GenericApplicationContext - Bean factory for org.springframework.context.support.GenericApplicationContext@19dc67c2: org.springframework.beans.factory.support.DefaultListableBeanFactory@d706f19: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,springTcfOnJunit5Test.LocalTestContext]; root of factory hierarchy
00:29:19.372 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
00:29:19.372 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
00:29:19.384 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Eagerly caching bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor' to allow for resolving potential circular references
00:29:19.387 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
00:29:19.467 [main] DEBUG org.springframework.context.annotation.ConfigurationClassEnhancer - Successfully enhanced com.example.spring5testdemo.SpringTcfOnJunit5Test$LocalTestContext; enhanced class name is: com.example.spring5testdemo.SpringTcfOnJunit5Test$LocalTestContext$$EnhancerBySpringCGLIB$$4923939c
00:29:19.468 [main] DEBUG org.springframework.context.annotation.ConfigurationClassPostProcessor - Replacing bean definition 'springTcfOnJunit5Test.LocalTestContext' existing class 'com.example.spring5testdemo.SpringTcfOnJunit5Test$LocalTestContext' with enhanced class 'com.example.spring5testdemo.SpringTcfOnJunit5Test$LocalTestContext$$EnhancerBySpringCGLIB$$4923939c'
00:29:19.471 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
00:29:19.471 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
00:29:19.472 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Eagerly caching bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor' to allow for resolving potential circular references
00:29:19.496 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
00:29:19.496 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalRequiredAnnotationProcessor'
00:29:19.496 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.context.annotation.internalRequiredAnnotationProcessor'
00:29:19.496 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Eagerly caching bean 'org.springframework.context.annotation.internalRequiredAnnotationProcessor' to allow for resolving potential circular references
00:29:19.500 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.context.annotation.internalRequiredAnnotationProcessor'
00:29:19.500 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
00:29:19.500 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
00:29:19.505 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Eagerly caching bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor' to allow for resolving potential circular references
00:29:19.509 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
00:29:19.511 [main] DEBUG org.springframework.context.support.GenericApplicationContext - Unable to locate MessageSource with name 'messageSource': using default [org.springframework.context.support.DelegatingMessageSource@79d8407f]
00:29:19.513 [main] DEBUG org.springframework.context.support.GenericApplicationContext - Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [org.springframework.context.event.SimpleApplicationEventMulticaster@5aebe890]
00:29:19.514 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@d706f19: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,springTcfOnJunit5Test.LocalTestContext]; root of factory hierarchy
00:29:19.514 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
00:29:19.514 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
00:29:19.514 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.annotation.internalRequiredAnnotationProcessor'
00:29:19.514 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
00:29:19.515 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
00:29:19.515 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.context.event.internalEventListenerProcessor'
00:29:19.521 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Eagerly caching bean 'org.springframework.context.event.internalEventListenerProcessor' to allow for resolving potential circular references
00:29:19.522 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.context.event.internalEventListenerProcessor'
00:29:19.523 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
00:29:19.523 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'org.springframework.context.event.internalEventListenerFactory'
00:29:19.523 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Eagerly caching bean 'org.springframework.context.event.internalEventListenerFactory' to allow for resolving potential circular references
00:29:19.525 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'org.springframework.context.event.internalEventListenerFactory'
00:29:19.525 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'springTcfOnJunit5Test.LocalTestContext'
00:29:19.525 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'springTcfOnJunit5Test.LocalTestContext'
00:29:19.525 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Eagerly caching bean 'springTcfOnJunit5Test.LocalTestContext' to allow for resolving potential circular references
00:29:19.527 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'springTcfOnJunit5Test.LocalTestContext'
00:29:19.527 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
00:29:19.545 [main] DEBUG org.springframework.context.support.GenericApplicationContext - Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor@a1cdc6d]
00:29:19.545 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
00:29:19.547 [main] DEBUG org.springframework.core.env.PropertySourcesPropertyResolver - Could not find key 'spring.liveBeansView.mbeanDomain' in any property source
00:29:19.548 [main] DEBUG org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate - Storing ApplicationContext in cache under key [[MergedContextConfiguration@2d127a61 testClass = SpringTcfOnJunit5Test, locations = '{}', classes = '{class com.example.spring5testdemo.SpringTcfOnJunit5Test$LocalTestContext}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]
00:29:19.548 [main] DEBUG org.springframework.test.context.cache - Spring test ApplicationContext cache statistics: [DefaultContextCache@6236eb5f size = 1, maxSize = 32, parentContextCount = 0, hitCount = 0, missCount = 1]
00:29:19.552 [main] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected element of bean 'com.example.spring5testdemo.SpringTcfOnJunit5Test': AutowiredFieldElement for private org.springframework.context.ApplicationContext com.example.spring5testdemo.SpringTcfOnJunit5Test.applicationContext
00:29:19.556 [main] DEBUG org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - Autowiring by type from bean name 'com.example.spring5testdemo.SpringTcfOnJunit5Test' to bean named 'org.springframework.context.support.GenericApplicationContext@19dc67c2'
00:29:19.558 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test method: context [DefaultTestContext@69a10787 testClass = SpringTcfOnJunit5Test, testInstance = com.example.spring5testdemo.SpringTcfOnJunit5Test@11c20519, testMethod = defaultContextTest@SpringTcfOnJunit5Test, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@2d127a61 testClass = SpringTcfOnJunit5Test, locations = '{}', classes = '{class com.example.spring5testdemo.SpringTcfOnJunit5Test$LocalTestContext}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]], attributes = map[[empty]]], class annotated with @DirtiesContext [false] with mode [null], method annotated with @DirtiesContext [false] with mode [null].
00:29:19.559 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'messageSource'
00:29:19.560 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - After test method: context [DefaultTestContext@69a10787 testClass = SpringTcfOnJunit5Test, testInstance = com.example.spring5testdemo.SpringTcfOnJunit5Test@11c20519, testMethod = defaultContextTest@SpringTcfOnJunit5Test, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@2d127a61 testClass = SpringTcfOnJunit5Test, locations = '{}', classes = '{class com.example.spring5testdemo.SpringTcfOnJunit5Test$LocalTestContext}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]], attributes = map[[empty]]], class annotated with @DirtiesContext [false] with mode [null], method annotated with @DirtiesContext [false] with mode [null].
00:29:19.561 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - After test class: context [DefaultTestContext@69a10787 testClass = SpringTcfOnJunit5Test, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration@2d127a61 testClass = SpringTcfOnJunit5Test, locations = '{}', classes = '{class com.example.spring5testdemo.SpringTcfOnJunit5Test$LocalTestContext}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[[empty]], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]], attributes = map[[empty]]], class annotated with @DirtiesContext [false] with mode [null].
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.459 sec - in com.example.spring5testdemo.SpringTcfOnJunit5Test
00:29:19.565 [Thread-1] INFO org.springframework.context.support.GenericApplicationContext - Closing org.springframework.context.support.GenericApplicationContext@19dc67c2: startup date [Sun May 21 00:29:19 JST 2017]; root of context hierarchy
00:29:19.566 [Thread-1] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
00:29:19.566 [Thread-1] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@d706f19: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,springTcfOnJunit5Test.LocalTestContext]; root of factory hierarchy
Results :
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.369 s
[INFO] Finished at: 2017-05-21T00:29:19+09:00
[INFO] Final Memory: 19M/307M
[INFO] ------------------------------------------------------------------------
Note:
Lorsque vous utilisez
MockMvc
sur JUnit 5, ajoutezhamcrest-core
à la bibliothèque dépendante car le composant qui vérifie le résultat de l'exécution utilise le mécanismeMatcher
de Hamcrest.<dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-core</artifactId> <version>1.3</version> <scope>test</scope> </dependency>
@SpringJUnitConfig
Essayer:point_right:@SpringJUnitConfig
Est une annotation synthétique pour indiquer que Spring TestContext Framework est utilisé sur Junit 5(@ExtendWith(SpringExtension.class)
+ @ContextConfiguration
)Et si nécessaire@ContextConfiguration
Vous pouvez spécifier les attributs fournis par.
package com.example.spring5testdemo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
@SpringJUnitConfig // ★★★ Spécifiez au lieu de @ExtendWith (SpringExtension.class)
class SpringJUnitConfigOnJunit5Test {
@Autowired private ApplicationContext applicationContext;
@Test
void defaultContextTest() {
Assertions.assertEquals(1, applicationContext.getBeansOfType(MessageSource.class).size());
}
@Configuration
static class LocalTestContext {}
}
Si vous souhaitez modifier le comportement par défaut ...
Lors de l'utilisation de la classe JavaConfig fournie pour les tests
@SpringJUnitConfig(GlobalTestContext.class)
class SpringJUnitConfigOnJunit5Test {
// ...
}
Avec un sentiment comme@SpringJUnitConfig
Vous pouvez utiliser les attributs de.
@SpringJUnitWebConfig
Essayer:point_right:@SpringJUnitWebConfig
Est@SpringJUnitConfig
Dans la version WEB de@SpringJUnitConfig
La différence avec@WebAppConfiguration
A été accordé/Seule la différence ne l'est pas.
réellement@SpringJUnitWebConfig
Pour essayer, vous devez ajouter des bibliothèques dépendantes. En particulier····
est. Cette zone est nécessaire lors de la création ou de l'exécution de l'application à tester, donc je pense que c'est une partie dont vous n'avez généralement pas à vous soucier.
pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
Après avoir ajouté la bibliothèque@SpringJUnitWebConfig
Créez une classe de cas de test avec.
package com.example.spring5testdemo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;
import org.springframework.web.context.support.GenericWebApplicationContext;
@SpringJUnitWebConfig // ★★★ Spécifiez au lieu de @ExtendWith (SpringExtension.class)
class SpringJUnitWebConfigOnJunit5Test {
@Autowired private ApplicationContext applicationContext;
// Vous pouvez injecter Mock = @WebAppConfiguration fonctionne!
@Autowired private MockServletContext mockServletContext;
@Autowired private MockHttpSession mockHttpSession;
@Autowired private MockHttpServletRequest mockRequest;
@Test
void defaultContextTest() {
// ApplicationContext utilise également des classes Web = @WebAppConfiguration fonctionne!
Assertions.assertEquals(GenericWebApplicationContext.class, applicationContext.getClass());
Assertions.assertNotNull(mockServletContext);
Assertions.assertNotNull(mockHttpSession);
Assertions.assertNotNull(mockRequest);
Assertions.assertEquals(1, applicationContext.getBeansOfType(MessageSource.class).size());
}
@Configuration
static class LocalTestContext {}
}
@EnabledIf
Quand@DisabledIf
Essayer:point_right:@EnabledIf
"Répond aux conditions spécifiées (le résultat de l'expression spécifié par SpEL esttrue
Si vous souhaitez exécuter le test ",@DisabledIf
Est une annotation qui indique «ignorer le test lorsque la condition est remplie» et qui peut être spécifiée au niveau de la classe et au niveau de la méthode.
Dans cette entrée, lorsqu'il y a un test à effectuer et un test à ignorer si l'OS est Mac, nous utiliserons cette annotation pour contrôler l'exécution du test.
package com.example.spring5testdemo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit.jupiter.DisabledIf;
import org.springframework.test.context.junit.jupiter.EnabledIf;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
@SpringJUnitConfig
class XxxIfOnJunit5Test {
@Test
@EnabledIf("#{systemProperties['os.name'].toLowerCase().contains('mac')}")
void enableOnMac() {
// Testé lorsque l'OS est Mac
// ...
}
@Test
@DisabledIf("#{systemProperties['os.name'].toLowerCase().contains('mac')}")
void disableOnMac() {
// Le test est ignoré lorsque l'OS est Mac (= le test est effectué lorsque l'OS est autre que Mac)
// ...
}
@Configuration
static class LocalTestContext {}
}
$ mvn test
...
Tests run: 2, Failures: 0, Errors: 0, Skipped: 1, Time elapsed: 0.128 sec - in com.example.spring5testdemo.XxxIfOnJunit5Test
...
Conditions utilisées uniquement dans des cas de test spécifiques(expression)Ensuite, vous pouvez l'écrire dans l'ad hoc comme ci-dessus, mais si vous devez spécifier les mêmes conditions dans plusieurs tests,@EnabledIf
Ou@DisabledIf
Il est préférable de créer une annotation synthétique avec la méta-annotation.
Annotations pour activer les tests sur Mac
package com.example.spring5testdemo;
import org.springframework.test.context.junit.jupiter.EnabledIf;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@EnabledIf("#{systemProperties['os.name'].toLowerCase().contains('mac')}")
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface EnabledOnMac {
}
Annotation pour sauter les tests sur Mac
package com.example.spring5testdemo;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.test.context.junit.jupiter.DisabledIf;
@DisabledIf("#{systemProperties['os.name'].toLowerCase().contains('mac')}")
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DisabledOnMac {
}
Code de test
@Test
@EnabledOnMac // ★★★ Spécifiez l'annotation synthétique créée et partagez la condition d'activation
void enableOnMac() {
// ...
}
@Test
@DisabledOnMac // ★★★ Spécifiez l'annotation synthétique créée et partagez la condition de saut
void disableOnMac() {
// ...
}
#Peut exécuter des tests en parallèle à l'aide de Spring TestContext Framework:thumbsup:
[SPR-5863]:SpringTestContextFramework(TCF)Vouspermetd'exécuterdestestsenutilisantenparallèle.Jevoulaisl'essayeravecJUnit5,mais...jenepouvaispascréer"rapidement"unenvironnementpouruneexécutionparallèle,j'aidoncdécidédel'essayeravecJUnit4uniquementici...:sweat_smile:(Pasmal) En plus, maven-surefire-Vous devez exclure temporairement la bibliothèque pour JUnit 5 des bibliothèques dépendantes du plugin.
Note:
Je vais l'introduire brièvement dans cette entrée, mais pour les restrictions et précautions lors de l'exécution parallèle, veuillez vous référer à "Référence de Spring Framework"Veuillez vous référer au.
pom.xml
<!-- ... -->
</dependencies>
<! - ★★★ Ajout de JUnit 4->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
<!-- ... -->
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<! - ★★★ Ajout du paramètre d'exécution parallèle (Exemple: Exécuter un scénario de test avec 3 threads sur 1JMV) ->
<configuration>
<parallel>methods</parallel>
<threadCount>3</threadCount>
</configuration>
</plugin>
</plugins>
</build>
<!-- ... -->
Préparez trois méthodes de test dans la classe de test.
package com.example.spring5testdemo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import java.util.concurrent.TimeUnit;
@RunWith(SpringRunner.class)
@WebAppConfiguration
public class ParallelTest {
@Autowired private ApplicationContext ac;
@Autowired private MockHttpServletRequest request;
@Test
public void one() throws InterruptedException {
TimeUnit.SECONDS.sleep(1);
System.out.println("★★★★one★★★★" + Thread.currentThread().getName() + " :" + this);
System.out.println("★★★★one★★★★" + Thread.currentThread().getName() + " :" + ac);
System.out.println("★★★★one★★★★" + Thread.currentThread().getName() + " :" + ac.getBean(Foo.class));
System.out.println("★★★★one★★★★" + Thread.currentThread().getName() + " :" + request);
}
@Test
public void two() throws InterruptedException {
TimeUnit.SECONDS.sleep(1);
System.out.println("★★★★two★★★★" + Thread.currentThread().getName() + " :" + this);
System.out.println("★★★★two★★★★" + Thread.currentThread().getName() + " :" + ac);
System.out.println("★★★★two★★★★" + Thread.currentThread().getName() + " :" + ac.getBean(Foo.class));
}
@Test
public void three() throws InterruptedException {
TimeUnit.SECONDS.sleep(1);
System.out.println("★★★★three★★★★" + Thread.currentThread().getName() + " :" + this);
System.out.println("★★★★three★★★★" + Thread.currentThread().getName() + " :" + ac);
System.out.println("★★★★three★★★★" + Thread.currentThread().getName() + " :" + ac.getBean(Foo.class));
System.out.println("★★★★three★★★★" + Thread.currentThread().getName() + " :" + request);
}
@Configuration
static class LocalTestContext {
@Bean
Foo foo() {
return new Foo();
}
}
static class Foo {}
}
Lorsque ce cas de test est exécuté, le journal suivant (extrait) sera sorti sur la console.
$ mvn test -Dtest=ParallelTest
...
★★★★three★★★★pool-1-thread-3 :com.example.spring5testdemo.ParallelTest@7ff7cced
★★★★three★★★★pool-1-thread-3 :org.springframework.web.context.support.GenericWebApplicationContext@128169a9: startup date [Sun May 21 17:49:56 JST 2017]; root of context hierarchy
17:49:57.966 [pool-1-thread-3] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'foo'
★★★★three★★★★pool-1-thread-3 :com.example.spring5testdemo.ParallelTest$Foo@11a551ce
★★★★three★★★★pool-1-thread-3 :org.springframework.mock.web.MockHttpServletRequest@2695d62a
...
★★★★two★★★★pool-1-thread-2 :com.example.spring5testdemo.ParallelTest@1fad7c69
★★★★two★★★★pool-1-thread-2 :org.springframework.web.context.support.GenericWebApplicationContext@128169a9: startup date [Sun May 21 17:49:56 JST 2017]; root of context hierarchy
17:49:57.966 [pool-1-thread-2] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'foo'
★★★★two★★★★pool-1-thread-2 :com.example.spring5testdemo.ParallelTest$Foo@11a551ce
★★★★two★★★★pool-1-thread-2 :org.springframework.mock.web.MockHttpServletRequest@7927bef5
...
★★★★one★★★★pool-1-thread-1 :com.example.spring5testdemo.ParallelTest@3693321f
★★★★one★★★★pool-1-thread-1 :org.springframework.web.context.support.GenericWebApplicationContext@128169a9: startup date [Sun May 21 17:49:56 JST 2017]; root of context hierarchy
17:49:57.966 [pool-1-thread-1] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'foo'
★★★★one★★★★pool-1-thread-1 :com.example.spring5testdemo.ParallelTest$Foo@11a551ce
★★★★one★★★★pool-1-thread-1 :org.springframework.mock.web.MockHttpServletRequest@5950ee9d
...
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.013 sec - in com.example.spring5testdemo.ParallelTest
...
Ce que vous pouvez voir dans ce journal ...
*Trois méthodes de cas de test s'exécutent en parallèle sur différents threads
*Une instance de la classe de cas de test est créée pour chaque méthode de cas de test
*InjecterApplicationContext
Est partagé dans chaque cas de test
*L'objet Mock d'injection est instancié pour chaque cas de test
à propos de ça.
Le point est ...ApplicationContext
Sera partagé. En exécution parallèle, les tests sont exécutés en même temps, donc s'il existe un cas de test qui met à jour l'état de l'objet géré par le conteneur DI, cela peut affecter le résultat de l'exécution d'un autre cas de test. De plus, bien que non limitée aux tests utilisant TCF, l'exécution parallèle de tests qui accèdent à des ressources externes (bases de données, fichiers, etc.) peut ne pas produire les résultats attendus.
De cette façon ... Est-il possible d'exécuter en parallèle? Notez que cela dépend de la création d'applications et de cas de test, donc si vous adoptez facilement l'exécution parallèle, des erreurs inattendues peuvent se produire.
#Ajout de méthodes de rappel qui sont appelées juste avant et immédiatement après l'exécution du test:thumbsup:
[SPR-4365]:TestExecutionListener
Uneméthodederappelquiestappeléesurl'interfaceimmédiatementavantetaprèsl'exécutiondutest.(beforeTestExecution
QuandafterTestExecution
)Sera ajouté.
Dans cette entrée, JUnit 5 est utilisé, et "pré-traitement et post-traitement fournis par le mécanisme de JUnit lui-même" et "Spring TestContext Framework".(TCF)Introduction de l'ordre du "prétraitement et post-traitement fourni par le mécanisme de".
package com.example.spring5testdemo;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.TestExecutionListener;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
@SpringJUnitConfig
@TestExecutionListeners (TestExecutionListenerTest.MyTestExecutionListener.class) // ★★★ Spécifie la classe d'implémentation de TestExecutionListener
class TestExecutionListenerTest {
// ------------------------------------
// Prétraitement et post-traitement fournis par le mécanisme de JUnit lui-même
// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
@BeforeAll
static void beforeAll(TestInfo testInfo) {
System.out.println("beforeAll");
}
@BeforeEach
void beforeEach(TestInfo testInfo) {
System.out.println(testInfo.getTestMethod().get().getName() + "-beforeEach");
}
@AfterEach
void afterEach(TestInfo testInfo) {
System.out.println(testInfo.getTestMethod().get().getName() + "-afterEach");
}
@AfterAll
static void afterAll(TestInfo testInfo) {
System.out.println("afterAll");
}
// ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
// Prétraitement et post-traitement fournis par le mécanisme de JUnit lui-même
// ------------------------------------
// ------------
// Méthode d'essai
// ↓↓↓↓↓↓↓↓↓↓
@Test
void test1() {
System.out.println("test1");
}
@Test
void test2() {
System.out.println("test2");
}
// ↑↑↑↑↑↑↑↑↑↑
// Méthode d'essai
// ------------
// ------------------------------------------------------------
// Pré-traitement et post-traitement fournis par le mécanisme de Spring TestContext Framework (TCF)
// ------------------------------------------------------------
static class MyTestExecutionListener implements TestExecutionListener {
@Override
public void beforeTestClass(TestContext testContext) throws Exception {
System.out.println("beforeTestClass");
}
@Override
public void prepareTestInstance(TestContext testContext) throws Exception {
System.out.println("prepareTestInstance");
}
@Override
public void beforeTestMethod(TestContext testContext) throws Exception {
System.out.println(testContext.getTestMethod().getName() + "-beforeTestMethod");
}
@Override // ★★★ Méthodes ajoutées dans la version 5.0
public void beforeTestExecution(TestContext testContext) throws Exception {
System.out.println(testContext.getTestMethod().getName() + "-beforeTestExecution");
}
@Override // ★★★ Méthodes ajoutées dans la version 5.0
public void afterTestExecution(TestContext testContext) throws Exception {
System.out.println(testContext.getTestMethod().getName() + "-afterTestExecution");
}
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
System.out.println(testContext.getTestMethod().getName() + "-afterTestMethod");
}
@Override
public void afterTestClass(TestContext testContext) throws Exception {
System.out.println("afterTestClass");
}
}
@Configuration
static class LocalTestContext {}
}
Lorsque j'exécute le test ci-dessus, j'obtiens la sortie de console suivante:
12:01:15.250 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
12:01:15.250 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
12:01:15.250 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.example.spring5testdemo.TestExecutionListenerTest] from class [org.springframework.test.context.support.DefaultTestContextBootstrapper]
12:01:15.252 [main] DEBUG org.springframework.test.context.support.AbstractDelegatingSmartContextLoader - Delegating to GenericXmlContextLoader to process context configuration [ContextConfigurationAttributes@4f80542f declaringClass = 'com.example.spring5testdemo.TestExecutionListenerTest', classes = '{}', locations = '{}', inheritLocations = true, initializers = '{}', inheritInitializers = true, name = [null], contextLoaderClass = 'org.springframework.test.context.ContextLoader'].
12:01:15.253 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.example.spring5testdemo.TestExecutionListenerTest]: class path resource [com/example/spring5testdemo/TestExecutionListenerTest-context.xml] does not exist
12:01:15.253 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.example.spring5testdemo.TestExecutionListenerTest]: no resource found for suffixes {-context.xml}.
12:01:15.253 [main] DEBUG org.springframework.test.context.support.AbstractDelegatingSmartContextLoader - Delegating to AnnotationConfigContextLoader to process context configuration [ContextConfigurationAttributes@4f80542f declaringClass = 'com.example.spring5testdemo.TestExecutionListenerTest', classes = '{}', locations = '{}', inheritLocations = true, initializers = '{}', inheritInitializers = true, name = [null], contextLoaderClass = 'org.springframework.test.context.ContextLoader'].
12:01:15.254 [main] DEBUG org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Ignoring class [com.example.spring5testdemo.TestExecutionListenerTest$MyTestExecutionListener]; it must be static, non-private, non-final, and annotated with @Configuration to be considered a default configuration class.
12:01:15.254 [main] INFO org.springframework.test.context.support.AbstractDelegatingSmartContextLoader - AnnotationConfigContextLoader detected default configuration classes for context configuration [ContextConfigurationAttributes@4f80542f declaringClass = 'com.example.spring5testdemo.TestExecutionListenerTest', classes = '{class com.example.spring5testdemo.TestExecutionListenerTest$LocalTestContext}', locations = '{}', inheritLocations = true, initializers = '{}', inheritInitializers = true, name = [null], contextLoaderClass = 'org.springframework.test.context.ContextLoader'].
12:01:15.255 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.example.spring5testdemo.TestExecutionListenerTest]
12:01:15.258 [main] INFO org.springframework.test.context.support.DefaultTestContextBootstrapper - Using TestExecutionListeners: [com.example.spring5testdemo.TestExecutionListenerTest$MyTestExecutionListener@130c12b7]
beforeTestClass
beforeAll
prepareTestInstance
test2-beforeTestMethod
test2-beforeEach
test2-beforeTestExecution ← Méthode ajoutée dans la version 5.0
test2
test2-afterTestExecution ← Méthodes ajoutées dans la version 5.0
test2-afterEach
test2-afterTestMethod
prepareTestInstance
test1-beforeTestMethod
test1-beforeEach
test1-beforeTestExecution ← Méthode ajoutée dans la version 5.0
test1
test1-afterTestExecution ← Méthodes ajoutées dans la version 5.0
test1-afterEach
test1-afterTestMethod
afterAll
afterTestClass
Au fait ... TCF le fournit par défautTestExecutionListener
Si vous souhaitez l'utiliser avec la classe d'implémentation de, vous devez spécifier le mode de fusion. (Probablement, il y a de nombreux cas où vous souhaitez l'utiliser ensemble)
@SpringJUnitConfig
@TestExecutionListeners(listeners = TestExecutionListenerTest.MyTestExecutionListener.class,
mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) // Changer mergeMode (il sera remplacé s'il est laissé par défaut)
class TestExecutionListenerTest {
// ...
}
MockHttpServletRequest
Une méthode pour obtenir la requête BODY est ajoutée à:thumbsup:[SPR-14717]:MockHttpServletRequest
MéthodepouraccéderàlarequêteBODY(getContentAsByteArray
QuandgetContentAsString
)Sera ajouté. Cette correspondance sera expliquée plus loin dans "MockMvc
La requête BODY est sortie dans le résultat du test au moment de l'utilisation:thumbsup:」を対応するために行われたものです。正直・・・このメソッドを個別に使うこQuandはほQuandんどないQuand思うので、サンプルを交えた説明は割愛させていただきます。
MockMvc
La requête BODY est sortie dans le résultat du test au moment de l'utilisation:thumbsup:[SPR-14717]:MockMvc
Lorsdelasortiedurésultatdutestaumomentdel'utilisationsurlaconsoleoulejournal(MockMvcResultHandlers
deprint
Oulog
Lorsdel'utilisationdelaméthode)De plus, la requête BODY sera également sortie.
Voyons précisément "quoi" et "comment" sont produits.
Avant ça ...MockMvc
Pour utiliser le ressort-Vous devez ajouter webmvc aux bibliothèques dépendantes.
pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
Après avoir ajouté les bibliothèques dépendantes, créez un contrôleur et un scénario de test pour les tests.
package com.example.spring5testdemo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.filter.CharacterEncodingFilter;
import java.nio.charset.StandardCharsets;
import java.util.List;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;
class MvcMockTest {
private MockMvc mockMvc;
@BeforeEach
void setupMockMvc() {
mockMvc = MockMvcBuilders.standaloneSetup(new WelcomeRestController())
.addFilter(new CharacterEncodingFilter(StandardCharsets.UTF_8.name()))
.build();
}
@Test
void test() throws Exception {
mockMvc.perform(post("/post").contentType(MediaType.APPLICATION_FORM_URLENCODED)
.content ("foo = bar") // ★★★ ← Ce sera affiché
.param("foo", "baz")
).andExpect(
status().isOk()
).andExpect(
result -> Assertions.assertEquals("[baz, bar]", result.getResponse().getContentAsString())
// content (). string ("[baz, bar]") // Si Hamcrest est sur le chemin de la classe, vous pouvez l'écrire comme ceci
).andDo(
print () // sortie de la console
).andDo(
log () // Sortie du journal
);
}
@RestController
static class WelcomeRestController {
@PostMapping("/post")
String post(@RequestParam List<String> foo) {
return foo.toString();
}
}
}
Lorsque vous exécutez le test créé, le résultat de l'exécution du test est émis vers la console ou le fichier journal.
print()Résultat de sortie de(console)
MockHttpServletRequest:
HTTP Method = POST
Request URI = /post
Parameters = {foo=[baz, bar]}
Headers = {Content-Type=[application/x-www-form-urlencoded;charset=UTF-8]}
Body = foo = bar ★★★ ← Ceci est la sortie de 5.0
Session Attrs = {}
Handler:
Type = com.example.spring5testdemo.MvcMockTest$WelcomeController
Method = java.lang.String com.example.spring5testdemo.MvcMockTest$WelcomeRestController.post(java.util.List<java.lang.String>)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[text/plain;charset=ISO-8859-1], Content-Length=[10]}
Content type = text/plain;charset=ISO-8859-1
Body = [baz, bar]
Forwarded URL = null
Redirected URL = null
Cookies = []
log()Résultat de sortie (console, fichier journal, etc.)
14:36:46.179 [main] DEBUG org.springframework.test.web.servlet.result - MvcResult details:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /post
Parameters = {foo=[baz, bar]}
Headers = {Content-Type=[application/x-www-form-urlencoded;charset=UTF-8]}
Body = foo = bar ★★★ ← Ceci est la sortie de 5.0
Session Attrs = {}
Handler:
Type = com.example.spring5testdemo.MvcMockTest$WelcomeController
Method = java.lang.String com.example.spring5testdemo.MvcMockTest$WelcomeRestController.post(java.util.List<java.lang.String>)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[text/plain;charset=ISO-8859-1], Content-Length=[10]}
Content type = text/plain;charset=ISO-8859-1
Body = [baz, bar]
Forwarded URL = null
Redirected URL = null
Cookies = []
Au fait ...print()
Oulog()
Si vous souhaitez appliquer à tous les cas de test,AbstractMockMvcBuilder
Est mis en œuvre dansalwaysDo
Utilisons la méthode.
@BeforeEach
void setupMockMvc() {
mockMvc = MockMvcBuilders.standaloneSetup(new WelcomeRestController())
.addFilter(new CharacterEncodingFilter(StandardCharsets.UTF_8.name()))
.alwaysDo (print ()) // Aller ici
.alwaysDo (log ()) // Allez ici
.build();
}
MockMvc
Le modèle d'URI peut être utilisé lors de la vérification de "URL de destination de redirection" et "URL de destination de transfert" au moment de l'utilisation:thumbsup:[SPR-14790]:MockMvc
Vouspourrezspécifierunmodèled'URIpourlavaleurattenduelorsdelavérificationde«l'URLdedestinationderedirection»etde«l'URLdedestinationderedirection»lorsdesonutilisation.(Personnellement,jenepensepasavoirbeaucoupdechanced'utiliser"l'URLdedestination".)
package com.example.spring5testdemo;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.stereotype.Controller;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.filter.CharacterEncodingFilter;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
class MvcMockTransitionTest {
private MockMvc mockMvc;
@BeforeEach
void setupMockMvc() {
mockMvc = MockMvcBuilders.standaloneSetup(new TransitionController())
.addFilter(new CharacterEncodingFilter(StandardCharsets.UTF_8.name()))
.build();
}
@Test
void testRedirect() throws Exception {
mockMvc.perform(get("/redirect/{id}", 1))
.andExpect(
status().isFound()
).andExpect(
redirectedUrl ("/ transition / redirect / {id}", 1) // ★★★ Vérification de l'URL au moment de la redirection
);
}
@Test
void testForward() throws Exception {
mockMvc.perform(get("/forward/{id}", 1))
.andExpect(
status().isOk()
).andExpect(
forwardedUrl ("/ transition / forward / {id}", 1) // ★★★ Vérification de l'URL au moment du transfert
);
}
@Controller
static class TransitionController {
@GetMapping("/redirect/{id}")
String redirect(@PathVariable int id) {
return "redirect:/transition/redirect/{id}";
}
@GetMapping("/forward/{id}")
String forward(@PathVariable int id) {
return "forward: / transition / forward /" + id; // Personnellement, je n'écris pas ce genre de code ...
}
}
}
#La version prise en charge de XMLUnit est 2.Devenir 3
[SPR-14043]:LaversionpriseenchargedeXMLUnit,unebibliothèqueprenantenchargelavalidationXML,est2..Ilsera3(l'exempledecodeintroduitdanscetteentréeest2.0.Celaafonctionnémêmeà0).Regardsurleschangements2.Méthodedevérificationdelasériex(assertXxx)Hamcrest au lieu deMatcher
Semble être offert maintenant.
Au printemps TestMockMvc
Certains des composants qui vérifient les résultats du traitement pendant l'utilisation dépendent de XMLUnit.
Si vous souhaitez utiliser les fonctions qui dépendent de XMLUnit, vous devez ajouter XMLUnit à la bibliothèque dépendante comme suit.
pom.xml
<dependency>
<groupId>org.xmlunit</groupId>
<artifactId>xmlunit-core</artifactId>
<version>2.3.0</version>
<scope>test</scope>
</dependency>
package com.example.spring5testdemo;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.filter.CharacterEncodingFilter;
import java.nio.charset.StandardCharsets;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
class XmlunitTest {
private MockMvc mockMvc;
@BeforeEach
void setupMockMvc() {
mockMvc = MockMvcBuilders.standaloneSetup(new XmlRestController())
.addFilter(new CharacterEncodingFilter(StandardCharsets.UTF_8.name()))
.alwaysDo(log())
.build();
}
@Test
void test() throws Exception {
mockMvc.perform(get("/get"))
.andExpect(
status().isOk()
).andExpect(
content (). Xml ("<root> <a> test </a> </ root>") // ★★★ Évaluer comme un document XML (= Les différences entre les espaces et les sauts de ligne ne sont pas traitées comme des différences)
);
}
@RestController
static class XmlRestController {
@GetMapping("/get")
String get() {
return "<root> <a>test</a> </root>";
}
}
}
Note:
Le processus de vérification proprement dit est
XmlExpectationsHelper
Parce qu'il est délégué àMockMvc
Il est possible d'effectuer la même vérification dans des endroits autres que ceux ci-dessus.
#Résumé
Cette fois, j'ai présenté les principaux changements liés à Test. Après tout ... Le support JUnit 5 est la plus grande fonctionnalité. JUnit 5 fait référence à JUnit 4 comme JUnit Vintage(=Pas d'expression en arrière)Personnellement, j'aime le fait qu'il dise w Il est intéressant non seulement de parler du nom, mais aussi de pouvoir exécuter en même temps des "cas de test écrits en JUnit 5" et des "cas de test écrits en JUnit 4". (Les anciens livrables peuvent être transférés tels quels !! = Si vous avez une capacité de réserve, vous pouvez convertir en JUnit 5 au niveau du code !!). Maven(maven-surefire-plugin)Alors ...
pom.xml
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit-platform.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
</dependency>
<! - ★★★ ↓ Si vous ajoutez ceci, vous pouvez tester des cas de test écrits en JUnit 5 et JUnit 4 en même temps->
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>4.12.0-M4</version>
</dependency>
</dependencies>
</plugin>
Ce n'est pas grave si vous le faites ressentir comme ça.
Je me suis écarté de l'histoire de Spring Framework:sweat_smile:・ ・ ・ Les tests sont un élément très important dans le développement d'applications, et Spring Framework fournit également une multitude de fonctions de support pour la création de code de test. (Pour garder le planning dans un proche avenir) "Parce que je n'ai pas le temps, je vais reporter le test (= insister sur le fait que le contrôle de fonctionnement est un test)!" Il y a des gens, mais à la fin personne ne l'obtiendra, alors revoyez (ajustez) le calendrier et assurez-vous que le code de test est en place. Si vous souhaitez créer une application à l'aide de Spring,Référence de Spring Framework(Edition de test)Nousvousrecommandonsdelire".(Ilyenabeaucoup,maisw) La prochaine fois, je présenterai le framework Web (WebFlux) de Reactive Programming Model.
#Annexe: Spring Boot 2.Comment utiliser JUnit 5 avec 0
Ici, Spring Boot 2.JUnit 5 à 0(+JUnit 4)Je vais vous présenter comment utiliser (coexister). Fondamentalement, appliquez simplement ce qui a été décrit dans cette entrée à votre application Spring Boot.
*Créer un projet Spring Boot
$ curl -s https://start.spring.io/starter.tgz\
-d name=test-demo\
-d artifactId=test-demo\
-d baseDir=test-demo\
-d bootVersion=2.0.0.M1\
| tar -xzvf -
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>test-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>test-demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.M1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<junit-jupiter.version>5.0.0-M4</junit-jupiter.version> <!-- ★★★ Add ★★★ -->
<junit-platform.version>1.0.0-M4</junit-platform.version> <!-- ★★★ Add ★★★ -->
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- ★★★ Add start ★★★ -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit-jupiter.version}</version>
<scope>test</scope>
</dependency>
<!-- ★★★ Add end ★★★ -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- ★★★ Add start ★★★ -->
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit-platform.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit-jupiter.version}</version>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit.version}.0-M4</version>
</dependency>
</dependencies>
</plugin>
<!-- ★★★ Add end ★★★ -->
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
*Classe de cas de test pour JUnit 5(Cas de test vide)Création
package com.example.testdemo;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
@SpringBootTest
class TestDemoApplicationUsingJUnit5Tests {
@Test
void contextLoads() {
}
}
*Lancer le test
$ ./mvnw test
/usr/local/apps/test-demo
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building test-demo 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ test-demo ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ test-demo ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ test-demo ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /usr/local/apps/test-demo/src/test/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ test-demo ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.19.1:test (default-test) @ test-demo ---
-------------------------------------------------------
T E S T S
-------------------------------------------------------
19:23:22.969 [main] DEBUG org.springframework.test.context.junit4.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class com.example.testdemo.TestDemoApplicationTests]
19:23:22.973 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
19:23:22.978 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
19:23:22.990 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.example.testdemo.TestDemoApplicationTests] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
19:23:22.999 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.example.testdemo.TestDemoApplicationTests], using SpringBootContextLoader
19:23:23.002 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.example.testdemo.TestDemoApplicationTests]: class path resource [com/example/testdemo/TestDemoApplicationTests-context.xml] does not exist
19:23:23.002 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.example.testdemo.TestDemoApplicationTests]: class path resource [com/example/testdemo/TestDemoApplicationTestsContext.groovy] does not exist
19:23:23.002 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.example.testdemo.TestDemoApplicationTests]: no resource found for suffixes {-context.xml, Context.groovy}.
19:23:23.003 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.example.testdemo.TestDemoApplicationTests]: TestDemoApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
19:23:23.049 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.055 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
19:23:23.055 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
19:23:23.056 [main] DEBUG org.springframework.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
19:23:23.066 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Resolved classpath location [com/example/testdemo/] to resources [URL [file:/usr/local/apps/test-demo/target/test-classes/com/example/testdemo/], URL [file:/usr/local/apps/test-demo/target/classes/com/example/testdemo/]]
19:23:23.067 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Looking for matching resources in directory tree [/usr/local/apps/test-demo/target/test-classes/com/example/testdemo]
19:23:23.067 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Searching directory [/usr/local/apps/test-demo/target/test-classes/com/example/testdemo] for files matching pattern [/usr/local/apps/test-demo/target/test-classes/com/example/testdemo/*.class]
19:23:23.069 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Looking for matching resources in directory tree [/usr/local/apps/test-demo/target/classes/com/example/testdemo]
19:23:23.069 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Searching directory [/usr/local/apps/test-demo/target/classes/com/example/testdemo] for files matching pattern [/usr/local/apps/test-demo/target/classes/com/example/testdemo/*.class]
19:23:23.069 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Resolved location pattern [classpath*:com/example/testdemo/*.class] to resources [file [/usr/local/apps/test-demo/target/test-classes/com/example/testdemo/TestDemoApplicationTests.class], file [/usr/local/apps/test-demo/target/test-classes/com/example/testdemo/TestDemoApplicationUsingJUnit5Tests.class], file [/usr/local/apps/test-demo/target/classes/com/example/testdemo/TestDemoApplication.class]]
19:23:23.113 [main] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [/usr/local/apps/test-demo/target/classes/com/example/testdemo/TestDemoApplication.class]
19:23:23.114 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.example.testdemo.TestDemoApplication for test class com.example.testdemo.TestDemoApplicationTests
19:23:23.203 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.example.testdemo.TestDemoApplicationTests]: using defaults.
19:23:23.203 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
19:23:23.209 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
19:23:23.209 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
19:23:23.212 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
19:23:23.212 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@d35dea7, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@7770f470, org.springframework.test.context.support.DirtiesContextTestExecutionListener@5e5d171f, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@24313fcc, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@7d20d0b, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@77f1baf5, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@41a2befb, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@6c40365c, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@7bedc48a]
19:23:23.214 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.214 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.example.testdemo.TestDemoApplicationTests]
Running com.example.testdemo.TestDemoApplicationTests
19:23:23.244 [main] DEBUG org.springframework.test.context.junit4.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class com.example.testdemo.TestDemoApplicationTests]
19:23:23.245 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
19:23:23.245 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
19:23:23.245 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.example.testdemo.TestDemoApplicationTests] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
19:23:23.245 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.example.testdemo.TestDemoApplicationTests], using SpringBootContextLoader
19:23:23.246 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.example.testdemo.TestDemoApplicationTests]: class path resource [com/example/testdemo/TestDemoApplicationTests-context.xml] does not exist
19:23:23.246 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.example.testdemo.TestDemoApplicationTests]: class path resource [com/example/testdemo/TestDemoApplicationTestsContext.groovy] does not exist
19:23:23.246 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.example.testdemo.TestDemoApplicationTests]: no resource found for suffixes {-context.xml, Context.groovy}.
19:23:23.246 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.example.testdemo.TestDemoApplicationTests]: TestDemoApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
19:23:23.249 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.249 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
19:23:23.250 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
19:23:23.250 [main] DEBUG org.springframework.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
19:23:23.251 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.example.testdemo.TestDemoApplication for test class com.example.testdemo.TestDemoApplicationTests
19:23:23.258 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.example.testdemo.TestDemoApplicationTests]: using defaults.
19:23:23.258 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
19:23:23.258 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
19:23:23.259 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
19:23:23.260 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
19:23:23.260 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@50caa560, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@2a266d09, org.springframework.test.context.support.DirtiesContextTestExecutionListener@5ab9e72c, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@186f8716, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@1d8bd0de, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@45ca843, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@11c9af63, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@757acd7b, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@36b4fe2a]
19:23:23.260 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.260 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.294 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.294 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.295 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.295 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.296 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.296 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.299 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@693fe6c9 testClass = TestDemoApplicationTests, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration@34f5090e testClass = TestDemoApplicationTests, locations = '{}', classes = '{class com.example.testdemo.TestDemoApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@25359ed8, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@80ec1f8, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@709ba3fb], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map[[empty]]], class annotated with @DirtiesContext [false] with mode [null].
19:23:23.299 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.299 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.300 [main] DEBUG org.springframework.test.context.support.DependencyInjectionTestExecutionListener - Performing dependency injection for test context [[DefaultTestContext@693fe6c9 testClass = TestDemoApplicationTests, testInstance = com.example.testdemo.TestDemoApplicationTests@22e357dc, testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration@34f5090e testClass = TestDemoApplicationTests, locations = '{}', classes = '{class com.example.testdemo.TestDemoApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@25359ed8, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@80ec1f8, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@709ba3fb], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map[[empty]]]].
19:23:23.315 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
19:23:23.316 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
19:23:23.316 [main] DEBUG org.springframework.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
19:23:23.320 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=-1}
19:23:23.320 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [Inlined Test Properties] PropertySource with highest search precedence
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.0.M1)
2017-05-21 19:23:23.786 INFO 70579 --- [ main] c.e.testdemo.TestDemoApplicationTests : Starting TestDemoApplicationTests on Kazuki-no-MacBook-Pro.local with PID 70579 (started by shimizukazuki in /usr/local/apps/test-demo)
2017-05-21 19:23:23.788 INFO 70579 --- [ main] c.e.testdemo.TestDemoApplicationTests : No active profile set, falling back to default profiles: default
2017-05-21 19:23:23.807 INFO 70579 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@387a8303: startup date [Sun May 21 19:23:23 JST 2017]; root of context hierarchy
2017-05-21 19:23:24.135 INFO 70579 --- [ main] c.e.testdemo.TestDemoApplicationTests : Started TestDemoApplicationTests in 0.81 seconds (JVM running for 1.56)
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.973 sec - in com.example.testdemo.TestDemoApplicationTests
Running com.example.testdemo.TestDemoApplicationUsingJUnit5Tests
2017-05-21 19:23:24.242 INFO 70579 --- [ main] .b.t.c.SpringBootTestContextBootstrapper : Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.example.testdemo.TestDemoApplicationUsingJUnit5Tests], using SpringBootContextLoader
2017-05-21 19:23:24.242 INFO 70579 --- [ main] o.s.t.c.support.AbstractContextLoader : Could not detect default resource locations for test class [com.example.testdemo.TestDemoApplicationUsingJUnit5Tests]: no resource found for suffixes {-context.xml, Context.groovy}.
2017-05-21 19:23:24.242 INFO 70579 --- [ main] t.c.s.AnnotationConfigContextLoaderUtils : Could not detect default configuration classes for test class [com.example.testdemo.TestDemoApplicationUsingJUnit5Tests]: TestDemoApplicationUsingJUnit5Tests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
2017-05-21 19:23:24.244 INFO 70579 --- [ main] .b.t.c.SpringBootTestContextBootstrapper : Found @SpringBootConfiguration com.example.testdemo.TestDemoApplication for test class com.example.testdemo.TestDemoApplicationUsingJUnit5Tests
2017-05-21 19:23:24.247 INFO 70579 --- [ main] .b.t.c.SpringBootTestContextBootstrapper : Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
2017-05-21 19:23:24.247 INFO 70579 --- [ main] .b.t.c.SpringBootTestContextBootstrapper : Could not instantiate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
2017-05-21 19:23:24.247 INFO 70579 --- [ main] .b.t.c.SpringBootTestContextBootstrapper : Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
2017-05-21 19:23:24.247 INFO 70579 --- [ main] .b.t.c.SpringBootTestContextBootstrapper : Could not instantiate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
2017-05-21 19:23:24.248 INFO 70579 --- [ main] .b.t.c.SpringBootTestContextBootstrapper : Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@665e9289, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@7d3430a7, org.springframework.test.context.support.DirtiesContextTestExecutionListener@6f603e89, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@2756c0a7, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@350ec41e, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@69637b10, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@71984c3, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@165b2f7f, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@5536379e]
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.016 sec - in com.example.testdemo.TestDemoApplicationUsingJUnit5Tests
2017-05-21 19:23:24.258 INFO 70579 --- [ Thread-2] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@387a8303: startup date [Sun May 21 19:23:23 JST 2017]; root of context hierarchy
Results :
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.126 s
[INFO] Finished at: 2017-05-21T19:23:24+09:00
[INFO] Final Memory: 20M/347M
[INFO] ------------------------------------------------------------------------
Recommended Posts