[JAVA] Wichtige Änderungen im Zusammenhang mit Spring Framework 5.0 Test

Dies ist die fünfte Ausgabe der Reihe "Wichtige Änderungen an Spring Framework 5.0" und die wichtigsten Änderungen im Zusammenhang mit Test (neue Funktionen, Verbesserungen usw.). Ich möchte vorstellen.

Serie

Version zur Überprüfung des Betriebs

Testbezogene Änderungen

In Spring Framework 5.0 wurden die folgenden Änderungen an der Testfunktion vorgenommen.

Artikelnummer Änderungen
1 Spring TestContext Framework(TCF)ZuJUnit 5 JupiterWirdamverfügbarsein.[ZuDetails:arrow_right:]

Note: SpringExtensionKlasse,@SpringJUnitConfigAnmerkung,@SpringJUnitWebConfigAnmerkung,@EnabledIfAnmerkung,@DisabledIfEine Anmerkung wird hinzugefügt.
2 Ermöglicht die parallele Ausführung von Tests mit dem Spring TestContext Framework.[Zu Details:arrow_right:]
3 TestExecutionListenerEine Rückrufmethode, die unmittelbar vor und nach der Ausführung des Tests auf der Schnittstelle aufgerufen wird.(beforeTestExecutionWannafterTestExecution)Wird hinzugefügt werden.[Zu Details:arrow_right:]
4 MockHttpServletRequestMethode für den Zugriff auf den Anforderungskörper(getContentAsByteArrayWanngetContentAsString)Wird hinzugefügt werden.[Zu Details:arrow_right:]
5 MockMvcBei der Ausgabe des Testergebnisses zum Zeitpunkt der Verwendung an die Konsole oder das Protokoll(MockMvcResultHandlersvonprintOderlogBei Verwendung der Methode)Zusätzlich wird der Anforderungskörper ausgegeben.[Zu Details:arrow_right:]
6 MockMvcSie können eine URI-Vorlage für den erwarteten Wert angeben, wenn Sie die "Ziel-URL umleiten" und die Ziel-URL weiterleiten, wenn Sie sie verwenden.[Zu Details:arrow_right:]
7 Die Unterstützungsversion von XMLUnit, einer Bibliothek, die die XML-Validierung unterstützt, ist 2..Es wird 3 sein.[Zu Details:arrow_right:]

JUnit 5 unterstützt: thumbsup:

[SPR-13575]: Der Höhepunkt der testbezogenen Änderungen in Spring Framework 5.0 ist [JUnit 5 Jupiter](http :) //junit.org/junit5/) zu [Spring TestContext Framework (TCF)](http://docs.spring.io/spring/docs/5.0.0.RC1/spring-framework-reference/testing.html# Integrationstests) werden verfügbar sein. Speziell···

Klasse(Anmerkung) Erläuterung
SpringExtension "" Bereitgestellt von Junit 5Expansionspunkt(Extension)Dies ist eine Klasse, mit der Sie das Spring TestContext Framework unter Junit 5 verwenden können.
Am JUnit 4SpringRunnerSpringClassRuleOderSpringMethodRuleSpielen Sie die gleiche Rolle.
@SpringJUnitConfig Synthetische Annotation, um zu zeigen, dass Spring TestContext Framework unter Junit 5 verwendet wird(@ExtendWith(SpringExtension.class) + @ContextConfiguration)ist.
@SpringJUnitWebConfig Synthetische Annotation, um zu zeigen, dass Spring TestContext Framework für die WEB-Umgebung in Junit 5 verwendet wird(@ExtendWith(SpringExtension.class) + @ContextConfiguration + @WebAppConfiguration)ist.
@EnabledIf Erfüllen Sie die angegebenen Bedingungen (das von SpEL angegebene Ausdrucksergebnis isttrueEs ist eine Anmerkung, die angibt, dass der Test ausgeführt wird, wenn (wird).
@DisabledIf Erfüllen Sie die angegebenen Bedingungen (das von SpEL angegebene Ausdrucksergebnis isttrueEs ist eine Anmerkung, die angibt, dass der Test übersprungen wird, wenn (wird).

Wird hinzugefügt werden. Die Funktionen von TCF selbst sind sowohl für JUnit 4 als auch für JUnit 5 gleich, daher wird die Erläuterung der TCF-Funktionen in diesem Eintrag weggelassen. Nur die Methode zur Bereitstellung von TCF wird geändert.

Lassen Sie uns den Test am 5. Juni ausführen: Punch:

Dieser Eintrag erklärt Junit 5 nicht grundsätzlich, aber Sie benötigen eine Umgebung zum Testen auf Junit 5. Lassen Sie uns zunächst ein Maven-Projekt erstellen, das Junit 5 verwendet, und einen einfachen Test ausführen.

Erstellen Sie zunächst ein beliebiges Verzeichnis (Beispiel: / usr / local / apps / spring5-test-demo) und erstellen Sie die Verzeichnisstruktur in diesem Verzeichnis wie folgt.

$ mkdir -p /usr/local/apps/spring5-test-demo
$ cd /usr/local/apps/spring5-test-demo
...
$ tree
.
└── src
    ├── main
    │   ├── java
    │   └── resources
    └── test
        ├── java
        └── resources

Als nächstes erstellen Sie 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> <!--Spätestens zum Zeitpunkt des Schreibens ist 2.Es war 20, aber ich reduziere die Version, weil OutOfMemoryError angezeigt wird, wenn der Test fehlschlägt ...-->
        <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 mit OutOfMemoryError wird in der nächsten Meilensteinversion (5.0.0.M5) aufgelöst](https://github.com/junit-team) / junit5 / issue / 809).

Erstellen Sie abschließend eine Testklasse.

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");
	}

}

Sie können dieses Projekt auch in eine IDE importieren, die Junit 5 unterstützt, und die Funktionen der IDE verwenden, um Tests auf Junit 5 auszuführen. Hier verwenden wir jedoch das maven-sichere Fire-Plugin. Lassen Sie uns den Test ausführen.

$ 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] ------------------------------------------------------------------------

Versuchen Sie erneut, den Test auszuführen, damit er fehlschlägt.

@Test
void simpleTest() {
	Assertions.assertEquals("test", "fail"); //Immer einen Fehler bekommen
}
$ 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

Versuchen Sie Spring Extension: point_right:

Bei Verwendung von Spring TestContext Framework unter JUnit 5 muss "SpringExtension" angegeben werden. Um Spring Test verwenden zu können, muss pom.xml jedoch zunächst wie folgt geändert werden.

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)(Versionsnummer auf der Bom-Seite verwalten)-->
  <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-Test hinzufügen-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <scope>test</scope>
    </dependency>
    <!--★★★ Bibliothek für die Protokollausgabe(logback)Hinzufügen-->
    <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>

  <!--★★★ Fügen Sie ein Maven-Repository hinzu, das Spring-Snapshots bzw. Meilensteinversionen enthält-->
  <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:

Wenn Sie die Protokollausgabebibliothek nicht hinzufügen, wird beim Ausführen eines Tests mit dem maven-sure fire-plugin eine Fehlermeldung angezeigt. Warum bekommst du einen Fehler? Ich verstehe nicht, warum das Hinzufügen einer Bibliothek keinen Fehler verursacht ... Vorerst habe ich Spring's JIRA (SPR-15572) aufgelistet. Übrigens gab es keinen Fehler beim Ausführen des Tests mit der IntelliJ-Funktion. (Nicht mit Eclipse / STS ausprobiert)

Lassen Sie uns nach dem Hinzufügen der Bibliothek eine Testklasse erstellen.

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) //★★★ Geben Sie die Federverlängerung an
class SpringTcfOnJunit5Test {

	@Autowired private ApplicationContext applicationContext;

	@Test
	void defaultContextTest() {
		Assertions.assertEquals(1, applicationContext.getBeansOfType(MessageSource.class).size());
	}

	//Irgendwie Bean-Definitionsdatei(XML or JavaConfig)Wird benötigt, erstellen wir hier eine JavaConfig-Klasse als statische innere Klasse
	//Wenn Sie eine JavaConfig-Klasse als statische innere Klasse erstellen, erkennt TCF sie automatisch.
	@Configuration 
	static class LocalTestContext {}

}

Wenn Sie den Test ausführen ... wird das folgende Protokoll ausgegeben, und Sie können sehen, dass Spring TCF einen ApplicationContext (DI-Container) erstellt.

$ 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:

Wenn Sie "MockMvc" in JUnit 5 verwenden, fügen Sie der abhängigen Bibliothek "hamcrest-core" hinzu, da die Komponente, die das Ausführungsergebnis überprüft, den "Matcher" -Mechanismus von Hamcrest verwendet.

<dependency>
  <groupId>org.hamcrest</groupId>
  <artifactId>hamcrest-core</artifactId>
  <version>1.3</version>
  <scope>test</scope>
</dependency>

@SpringJUnitConfigVersuchen:point_right:

@SpringJUnitConfigIst eine synthetische Anmerkung, die angibt, dass das Spring TestContext Framework auf Junit 5 verwendet wird(@ExtendWith(SpringExtension.class) + @ContextConfiguration)Und wenn nötig@ContextConfigurationSie können die von angegebenen Attribute angeben.

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 // ★★★ Geben Sie anstelle von @ExtendWith (SpringExtension.class) an.
class SpringJUnitConfigOnJunit5Test {

	@Autowired private ApplicationContext applicationContext;

	@Test
	void defaultContextTest() {
		Assertions.assertEquals(1, applicationContext.getBeansOfType(MessageSource.class).size());
	}

	@Configuration
	static class LocalTestContext {}

}

Wenn Sie das Standardverhalten ändern möchten ...

Bei Verwendung der zum Testen bereitgestellten JavaConfig-Klasse


@SpringJUnitConfig(GlobalTestContext.class)
class SpringJUnitConfigOnJunit5Test {
	// ...
}

Mit einem Gefühl wie@SpringJUnitConfigSie können die Attribute von verwenden.

@SpringJUnitWebConfigVersuchen:point_right:

@SpringJUnitWebConfigIst@SpringJUnitConfigIn der WEB-Version von@SpringJUnitConfigDer Unterschied zu@WebAppConfigurationWurde gewährt/Nur der Unterschied ist nicht.

tatsächlich@SpringJUnitWebConfigUm dies zu versuchen, müssen Sie einige abhängige Bibliotheken hinzufügen. Speziell····

ist. Dieser Bereich ist erforderlich, wenn Sie die zu testende Anwendung erstellen oder ausführen. Ich denke, dass dies ein Teil ist, über den Sie sich normalerweise keine Sorgen machen müssen.

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>

Nach dem Hinzufügen der Bibliothek@SpringJUnitWebConfigErstellen Sie eine Testfallklasse mit.

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 // ★★★ Geben Sie anstelle von @ExtendWith (SpringExtension.class) an.
class SpringJUnitWebConfigOnJunit5Test {

	@Autowired private ApplicationContext applicationContext;

 // Sie können injizieren Mock = @WebAppConfiguration funktioniert!
	@Autowired private MockServletContext mockServletContext;
	@Autowired private MockHttpSession mockHttpSession;
	@Autowired private MockHttpServletRequest mockRequest;

	@Test
	void defaultContextTest() {
 // ApplicationContext verwendet auch Webklassen = @WebAppConfiguration funktioniert!
		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 {}

}

@EnabledIfWann@DisabledIfVersuchen:point_right:

@EnabledIf"Erfüllt die angegebenen Bedingungen (das von SpEL angegebene Ausdrucksergebnis isttrueWenn Sie den Test ausführen möchten ",@DisabledIfIst eine Anmerkung, die angibt, dass "der Test übersprungen wird, wenn die Bedingung erfüllt ist" und sowohl auf Klassen- als auch auf Methodenebene angegeben werden kann.

Wenn in diesem Eintrag ein Test durchgeführt und ein Test übersprungen werden muss, wenn das Betriebssystem ein Mac ist, wird diese Anmerkung verwendet, um die Ausführung des Tests zu steuern.

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() {
 // Getestet, wenn das Betriebssystem ein Mac ist
		// ...
	}

	@Test
	@DisabledIf("#{systemProperties['os.name'].toLowerCase().contains('mac')}")
	void disableOnMac() {
 // Der Test wird übersprungen, wenn das Betriebssystem Mac ist (= der Test wird durchgeführt, wenn das Betriebssystem nicht Mac ist)
		// ...
	}

	@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
...

Bedingungen, die nur in bestimmten Testfällen verwendet werden(expression)Dann können Sie es wie oben im Ad-hoc-Format schreiben. Wenn Sie jedoch in mehreren Tests dieselben Bedingungen angeben müssen,@EnabledIfOder@DisabledIfEs ist besser, eine synthetische Annotation mit der Meta-Annotation zu erstellen.

Anmerkungen zum Aktivieren des Testens auf dem 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 {
}

Anmerkung zum Überspringen von Tests auf dem 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 {
}

Testcode


@Test
 @EnabledOnMac // ★★★ Geben Sie die erstellte synthetische Anmerkung an und teilen Sie die Aktivierungsbedingung
void enableOnMac() {
	// ...
}

@Test
 @DisabledOnMac // ★★★ Geben Sie die erstellte synthetische Anmerkung an und teilen Sie die Überspringbedingung
void disableOnMac() {
	// ...
}

#Kann Tests parallel mit dem Spring TestContext Framework ausführen:thumbsup:

[SPR-5863]:SpringTestContextFramework(TCF)ErmöglichtdasparalleleAusführenvonTests.IchwollteesmitJUnit5versuchen,aber...ichkonntenicht"schnell"eineUmgebungfürdieparalleleAusführungerstellen,deshalbhabeichbeschlossen,esnurhiermitJUnit4zuversuchen...:sweat_smile:(Nichtschlecht) Außerdem Maven-surefire-Sie müssen die Bibliothek für JUnit 5 vorübergehend aus den abhängigen Bibliotheken des Plugins ausschließen.

Note:

Ich werde es in diesem Eintrag kurz vorstellen, aber für Einschränkungen und Vorsichtsmaßnahmen während der parallelen Ausführung siehe "Spring Framework Referenz"Bitte wende dich an die.

pom.xml


<!-- ... -->
</dependencies>
 <! - ★★★ JUnit 4-> hinzugefügt
  <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>
 <! - ★★★ Parallele Ausführungseinstellung hinzugefügt (Beispiel: Testfall mit 3 Threads auf 1JMV ausführen) ->
      <configuration>
        <parallel>methods</parallel>
        <threadCount>3</threadCount>
      </configuration>
    </plugin>
  </plugins>
</build>
<!-- ... -->

Bereiten Sie drei Testmethoden in der Testklasse vor.

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 {}

}

Wenn dieser Testfall ausgeführt wird, wird das folgende Protokoll (Auszug) auf der Konsole ausgegeben.

$ 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
...

Was Sie aus diesem Protokoll sehen können ...

*Drei Testfallmethoden werden parallel auf verschiedenen Threads ausgeführt *Für jede Testfallmethode wird eine Instanz der Testfallklasse erstellt *InjizierenApplicationContextWird in jedem Testfall geteilt *Das injizierende Mock-Objekt wird für jeden Testfall instanziiert

darüber. Der Punkt ist ...ApplicationContextWird geteilt. Bei der parallelen Ausführung werden die Tests gleichzeitig ausgeführt. Wenn also ein Testfall vorliegt, der den Status des vom DI-Container verwalteten Objekts aktualisiert, kann dies das Ausführungsergebnis eines anderen Testfalls beeinflussen. Auch wenn dies nicht auf Tests mit TCF beschränkt ist, führt die parallele Ausführung von Tests, die auf externe Ressourcen (Datenbanken, Dateien usw.) zugreifen, möglicherweise nicht zu den erwarteten Ergebnissen. Auf diese Weise ... Ist es möglich, parallel auszuführen? Beachten Sie, dass dies von der Erstellung von Anwendungen und Testfällen abhängt. Wenn Sie also problemlos die parallele Ausführung übernehmen, können unerwartete Fehler auftreten.

#Rückrufmethoden hinzugefügt, die unmittelbar vor und unmittelbar nach dem Ausführen des Tests aufgerufen werden:thumbsup:

[SPR-4365]:TestExecutionListenerEineRückrufmethode,dieunmittelbarvorundnachderAusführungdesTestsaufderSchnittstelleaufgerufenwird.(beforeTestExecutionWannafterTestExecution)Wird hinzugefügt werden.

In diesem Eintrag wird JUnit 5 verwendet und "Vor- und Nachbearbeitung durch den Mechanismus von JUnit selbst bereitgestellt" und "Spring TestContext Framework".(TCF)Einführung der Reihenfolge "Vorverarbeitung und Nachbearbeitung durch den Mechanismus von".

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) // ★★★ Geben Sie die Implementierungsklasse von TestExecutionListener an
class TestExecutionListenerTest {

	// ------------------------------------
 // Vor- und Nachbearbeitung durch den Mechanismus von JUnit selbst
	// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
	@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");
	}
	// ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
 // Vor- und Nachbearbeitung durch den Mechanismus von JUnit selbst
	// ------------------------------------

	// ------------
 // Testmethode
	// ↓↓↓↓↓↓↓↓↓↓
	@Test
	void test1() {
		System.out.println("test1");
	}
	@Test
	void test2() {
		System.out.println("test2");
	}
	// ↑↑↑↑↑↑↑↑↑↑
 // Testmethode
	// ------------

	// ------------------------------------------------------------
 // Vor- und Nachbearbeitung durch den Mechanismus des 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 // ★★★ In 5.0 hinzugefügte Methoden
		public void beforeTestExecution(TestContext testContext) throws Exception {
			System.out.println(testContext.getTestMethod().getName() + "-beforeTestExecution");
		}

 @Override // ★★★ In 5.0 hinzugefügte Methoden
		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 {}

}

Wenn ich den obigen Test ausführe, erhalte ich die folgende Konsolenausgabe:

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 ← In 5.0 hinzugefügte Methode
test2
 test2-afterTestExecution ← In 5.0 hinzugefügte Methoden
test2-afterEach
test2-afterTestMethod
prepareTestInstance
test1-beforeTestMethod
test1-beforeEach
 test1-beforeTestExecution ← In 5.0 hinzugefügte Methoden
test1
 test1-afterTestExecution ← In 5.0 hinzugefügte Methoden
test1-afterEach
test1-afterTestMethod
afterAll
afterTestClass

Übrigens ... TCF stellt es standardmäßig zur VerfügungTestExecutionListenerWenn Sie es mit der Implementierungsklasse von verwenden möchten, müssen Sie den Zusammenführungsmodus angeben. (Wahrscheinlich gibt es viele Fälle, in denen Sie es zusammen verwenden möchten.)

@SpringJUnitConfig
@TestExecutionListeners(listeners = TestExecutionListenerTest.MyTestExecutionListener.class,
 mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) // mergeMode ändern (wird ersetzt, wenn es als Standard beibehalten wird)
class TestExecutionListenerTest {
	// ...
}

MockHttpServletRequestEine Methode zum Abrufen des Anforderungskörpers wird hinzugefügt:thumbsup:

[SPR-14717]:MockHttpServletRequestMethodefürdenZugriffaufdenAnforderungskörper(getContentAsByteArrayWanngetContentAsString)Wird hinzugefügt werden. Diese Entsprechung wird später in "MockMvcRequest BODY wird zum Zeitpunkt der Verwendung im Testergebnis ausgegeben:thumbsup:」を対応するために行われたものです。正直・・・このメソッドを個別に使うこWannはほWannんどないWann思うので、サンプルを交えた説明は割愛させていただきます。

MockMvcRequest BODY wird zum Zeitpunkt der Verwendung im Testergebnis ausgegeben:thumbsup:

[SPR-14717]:MockMvcBeiderAusgabedesTestergebnisseszumZeitpunktderVerwendungandieKonsoleoderdasProtokoll(MockMvcResultHandlersvonprintOderlogBeiVerwendungderMethode)Zusätzlich wird der Anforderungskörper ausgegeben.

Lassen Sie uns speziell sehen, "was" und "wie" ausgegeben werden. Davor ...MockMvcFeder verwenden-Sie müssen den abhängigen Bibliotheken webmvc hinzufügen.

pom.xml


<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
</dependency>

Erstellen Sie nach dem Hinzufügen der abhängigen Bibliotheken einen Controller und einen Testfall zum Testen.

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") // ★★★ ← Dies wird ausgegeben
			.param("foo", "baz")
		).andExpect(
			status().isOk()
		).andExpect(
			result -> Assertions.assertEquals("[baz, bar]", result.getResponse().getContentAsString())
 // content (). string ("[baz, bar]") // Wenn sich Hamcrest im Klassenpfad befindet, können Sie es so schreiben
		).andDo(
 print () // Konsolenausgabe
		).andDo(
 log () // Protokollausgabe
		);
	}

	@RestController
	static class WelcomeRestController {
		@PostMapping("/post")
		String post(@RequestParam List<String> foo) {
			return foo.toString();
		}
	}

}

Wenn Sie den erstellten Test ausführen, wird das Ergebnis der Testausführung an die Konsole oder Protokolldatei ausgegeben.

print()Ausgabeergebnis von(Konsole)


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 ★★★ ← Dies wird von 5.0 ausgegeben
    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()Ausgabeergebnis (Konsole, Protokolldatei usw.)


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 ★★★ ← Dies wird von 5.0 ausgegeben
    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 = []

Apropos ...print()Oderlog()Wenn Sie sich auf alle Testfälle anwenden möchten,AbstractMockMvcBuilderIst implementiert inalwaysDoVerwenden wir die Methode.

@BeforeEach
void setupMockMvc() {
	mockMvc = MockMvcBuilders.standaloneSetup(new WelcomeRestController())
				.addFilter(new CharacterEncodingFilter(StandardCharsets.UTF_8.name()))
 .alwaysDo (print ()) // Hier klicken
 .alwaysDo (log ()) // Hier klicken
			.build();
}

MockMvcDie URI-Vorlage kann verwendet werden, wenn zum Zeitpunkt der Verwendung "Ziel-URL umleiten" und "Ziel-URL weiterleiten" überprüft wird:thumbsup:

[SPR-14790]:MockMvcSiekönneneineURI-VorlagefürdenerwartetenWertangeben,wennSiedie"Ziel-URLumleiten"unddieZiel-URLweiterleiten,wennSiesieverwenden.(Ichpersönlichglaubenicht,dassichdieChancehabe,die"Weiterleitungsziel-URL"zuverwenden.)

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) // ★★★ URL-Überprüfung zum Zeitpunkt der Weiterleitung
		);
	}

	@Test
	void testForward() throws Exception {
		mockMvc.perform(get("/forward/{id}", 1))
			.andExpect(
				status().isOk()
			).andExpect(
 forwardedUrl ("/ Transition / Forward / {ID}", 1) // ★★★ URL-Überprüfung zum Zeitpunkt der Weiterleitung
		);
	}

	@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; // Persönlich schreibe ich diese Art von Code grundsätzlich nicht ... (weil es ein Beispiel ist ...)
		}
	}

}

#Die Support-Version von XMLUnit ist 2.Werden Sie 3

[SPR-14043]:DieUnterstützungsversionvonXMLUnit,einerBibliothek,diedieXML-Validierungunterstützt,ist2..Eswird3sein(DerindiesemEintrageingeführteBeispielcodeist2.0.Eshatsogarbei0)funktioniert.BetrachtenSiedieÄnderungen2.Überprüfungsmethodeausx-Serien(assertXxx)Hamcrest stattMatcherScheint jetzt angeboten zu werden. Im FrühlingstestMockMvcEinige der Komponenten, die die Verarbeitungsergebnisse während der Verwendung überprüfen, hängen von XMLUnit ab.

Wenn Sie die von XMLUnit abhängigen Funktionen verwenden möchten, müssen Sie der abhängigen Bibliothek XMLUnit wie folgt hinzufügen.

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>") // ★★★ Als XML-Dokument auswerten (= Unterschiede zwischen Leerzeichen und Zeilenumbrüchen werden nicht als Unterschiede behandelt)
		);
	}

	@RestController
	static class XmlRestController {
		@GetMapping("/get")
		String get() {
			return "<root> <a>test</a> </root>";
		}
	}

}

Note:

Der eigentliche Überprüfungsprozess istXmlExpectationsHelperWeil es an delegiert istMockMvcEs ist möglich, dieselbe Überprüfung an anderen als den oben genannten Orten durchzuführen.

#Zusammenfassung

Dieses Mal habe ich die wichtigsten Änderungen in Bezug auf Test vorgestellt. Immerhin ... JUnit 5-Unterstützung ist das größte Feature. JUnit 5 bezeichnet JUnit 4 als JUnit Vintage(=Kein rückwärts gerichteter Ausdruck)Ich persönlich mag die Tatsache, dass dort steht: w Es ist attraktiv, nicht nur über den Namen zu sprechen, sondern auch gleichzeitig "in JUnit 5 geschriebene Testfälle" und "in JUnit 4 geschriebene Testfälle" ausführen zu können. (Frühere Leistungen können unverändert übertragen werden !! = Wenn Sie über freie Kapazität verfügen, können Sie auf Codeebene auf JUnit 5 konvertieren !!). Maven(maven-surefire-plugin)Dann ...

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>
 <! - ★★★ ↓ Wenn Sie dies hinzufügen, können Sie Testfälle testen, die in JUnit 5 und JUnit 4 gleichzeitig geschrieben wurden->
    <dependency>
      <groupId>org.junit.vintage</groupId>
      <artifactId>junit-vintage-engine</artifactId>
      <version>4.12.0-M4</version>
    </dependency>
  </dependencies>
</plugin>

Es ist in Ordnung, wenn Sie es so fühlen lassen.

Ich bin von der Geschichte von Spring Framework abgewichen:sweat_smile:... Das Testen ist ein sehr wichtiges Element in der Anwendungsentwicklung, und das Spring Framework bietet auch eine Vielzahl von Unterstützungsfunktionen zum Erstellen von Testcode. (Um den Zeitplan in naher Zukunft einzuhalten) "Da ich keine Zeit habe, werde ich den Test verschieben (= darauf bestehen, dass die Funktionsprüfung ein Test ist)!" Es gibt Leute, aber am Ende wird es niemand bekommen. Überprüfen (passen) Sie den Zeitplan an und stellen Sie sicher, dass Sie den Testcode installiert haben. Wenn Sie eine Anwendung mit Spring erstellen möchten,Spring Framework Referenz(Testausgabe)WirempfehlenIhnen,"zulesen.(Esgibtziemlichviel,aberw) Nächstes Mal werde ich das Web Framework (WebFlux) des Reactive Programming Model vorstellen.

#Anhang: Spring Boot 2.Verwendung von JUnit 5 mit 0

Hier Spring Boot 2.Einheit 5 bei 0(+JUnit 4)Ich werde vorstellen, wie man verwendet (koexistiert). Wenden Sie einfach das, was in diesem Eintrag beschrieben wurde, auf Ihre Spring Boot-Anwendung an.

*Erstellen eines Spring Boot-Projekts

$ 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>

*Testfallklasse für JUnit 5(Testfall leeren)Schaffung

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() {
	}

}

*Führen Sie den Test aus

$ ./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

Wichtige Änderungen im Zusammenhang mit Spring Framework 5.0 Test
Wichtige Änderungen in Bezug auf Spring Framework 5.0 Web MVC
Wichtige Änderungen im Zusammenhang mit dem Spring Framework 5.0 DI-Container
Spring Framework 5.0 Zusammenfassung der wichtigsten Änderungen
Wichtige Änderungen in der Kernfunktionalität von Spring Framework 5.0
Wichtige Änderungen in Spring Boot 1.5
So führen Sie einen Komponententest für Spring AOP durch
Testen Sie den Spring Framework Controller mit Junit
Änderungen bei der Migration von Spring Boot 1.5 auf Spring Boot 2.0
Änderungen bei der Migration von Spring Boot 2.0 zu Spring Boot 2.2
Ich habe versucht, JavaFX und Spring Framework zu verknüpfen.
So schreiben Sie einen Komponententest für Spring Boot 2
Verwendung von Struts2 * Spring Framework (Spring Plugin) Version Juni 2017
So testen Sie den Bildschirm zum Hochladen von Dateien mit Spring + Selenium
[Spring Framework] Konfigurationsaufteilung
Mehrsprachige Unterstützung für Spring Framework
Änderungen von Java 8 zu Java 11
1. Starten Sie Spring Framework von 1
Spring Framework Zusammenfassung - Über DI
Spielen Sie den Framework-Lerntest
Spring Framework 5.2.0 - Unterschiedliche Header-Duplizierung aufgrund einer Änderung der CORS-Behandlung