[JAVA] Major changes related to Spring Framework 5.0 Test

This is the 5th installment of the "Spring Framework 5.0 Major Changes" series, and the main changes related to Test (new features, improvements, etc.) I would like to introduce.

series

Operation verification version

Test related changes

In Spring Framework 5.0, the following changes have been made to the test function.

Item number Changes
1 Spring TestContext Framework(TCF)ToJUnit 5 JupiterWillbeavailableon.[Todetails:arrow_right:]

Note: SpringExtensionclass,@SpringJUnitConfigAnnotation,@SpringJUnitWebConfigAnnotation,@EnabledIfAnnotation,@DisabledIfAnnotation is added.
2 You will be able to run tests using the Spring TestContext Framework in parallel.[To details:arrow_right:]
3 TestExecutionListenerCallback methods that are called on the interface just before and after running the test(beforeTestExecutionWhenafterTestExecution)Will be added.[To details:arrow_right:]
4 MockHttpServletRequestMethod to access the request BODY(getContentAsByteArrayWhengetContentAsString)Will be added.[To details:arrow_right:]
5 MockMvcWhen outputting the test result at the time of use to the console or log(MockMvcResultHandlersofprintOrlogWhen using the method)In addition, the request BODY will also be output.[To details:arrow_right:]
6 MockMvcWhen verifying the "redirect destination URL" and "forward destination URL" at the time of use, it becomes possible to specify a URI template for the expected value.[To details:arrow_right:]
7 Support version 2 of XMLUnit, a library that supports XML validation.It will be 3.[To details:arrow_right:]

JUnit 5 supported: thumbsup:

[SPR-13575]: The highlight of the test-related changes in Spring Framework 5.0 is, after all, [JUnit 5 Jupiter](http:: //junit.org/junit5/) on [Spring TestContext Framework (TCF)](http://docs.spring.io/spring/docs/5.0.0.RC1/spring-framework-reference/testing.html# integration-testing) will be available. In particular···

class(Annotation) Description
SpringExtension "" Provided by Junit 5Expansion point(Extension)This is a class that enables you to use Spring TestContext Framework on Junit 5.
On JUnit 4SpringRunnerSpringClassRuleOrSpringMethodRulePlay the same role.
@SpringJUnitConfig Synthetic annotation to show that Spring TestContext Framework is used on Junit 5(@ExtendWith(SpringExtension.class) + @ContextConfiguration)is.
@SpringJUnitWebConfig Synthetic annotation to show that Spring TestContext Framework for WEB environment is used on Junit 5(@ExtendWith(SpringExtension.class) + @ContextConfiguration + @WebAppConfiguration)is.
@EnabledIf Satisfy the specified conditions (Expression result specified by SpEL istrueIt is an annotation indicating that the test is executed when (becomes).
@DisabledIf Satisfy the specified conditions (Expression result specified by SpEL istrueIt is an annotation indicating that the test is skipped when (becomes).

Will be added. The functions of TCF itself are the same on JUnit 4 and JUnit 5, so the explanation of TCF functions is omitted in this entry. Only the method for making TCF available will change.

Let's run the test with Junit 5: punch:

This entry doesn't basically explain Junit 5, but you need an environment to test on Junit 5. So ... for now, let's create a Maven project that uses Junit 5 and run a simple test.

First, create an arbitrary directory (example: / usr / local / apps / spring5-test-demo), and make the directory structure in that directory as follows.

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

Next, create 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> <!--The latest at the time of writing is 2.It was 20, but I am lowering the version because OutOfMemoryError appears when the test fails ...-->
        <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 with ʻOutOfMemoryError` will be resolved in the next milestone release (5.0.0.M5)](https://github.com/junit-team) / junit5 / issues / 809).

Finally, create a test class.

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

}

You can also import this project into an IDE that supports Junit 5 and use the features of the IDE to run tests on Junit 5, but here we use the maven-surefire-plugin. Let's run the test.

$ mvn test
[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building spring5-test-demo 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ spring5-test-demo ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ spring5-test-demo ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ spring5-test-demo ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /usr/local/apps/spring5-test-demo/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ spring5-test-demo ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 1 source file to /usr/local/apps/spring5-test-demo/target/test-classes
[INFO] 
[INFO] --- maven-surefire-plugin:2.19.1:test (default-test) @ spring5-test-demo ---

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.example.spring5testdemo.SimpleJunit5Test
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec - in com.example.spring5testdemo.SimpleJunit5Test

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.532 s
[INFO] Finished at: 2017-05-20T21:49:02+09:00
[INFO] Final Memory: 17M/300M
[INFO] ------------------------------------------------------------------------

Try running the test again so that it fails.

@Test
void simpleTest() {
	Assertions.assertEquals("test", "fail"); //Always get an error
}
$ 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

Try Spring Extension: point_right:

When using Spring TestContext Framework on JUnit 5, it is necessary to specify SpringExtension, but first you need to modify pom.xml as follows to be able to use Spring Test.

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)(Manage version number on bom side)-->
  <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-Add test-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <scope>test</scope>
    </dependency>
    <!--★★★ Library for log output(logback)To add-->
    <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>

  <!--★★★ Add Maven repositories containing Spring snapshots and milestone versions respectively-->
  <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:

If you do not add the log output library, you will get an error when running the test using maven-surefire-plugin. Why do you get an error? I don't understand why adding a library doesn't cause an error ... I've listed Spring's JIRA (SPR-15572) for the time being. By the way, there was no error when running the test with the IntelliJ feature. (I haven't tried it in Eclipse / STS)

After adding the library, let's actually create a test class.

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) //★★★ Specify Spring Extension
class SpringTcfOnJunit5Test {

	@Autowired private ApplicationContext applicationContext;

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

	//Somehow Bean definition file(XML or JavaConfig)Is required, so here we will create a JavaConfig class as a static inner class.
	//If you create a JavaConfig class as a static inner class, TCF will automatically detect it.
	@Configuration 
	static class LocalTestContext {}

}

When I run the test ... I get the following log, and I can see that Spring TCF is generating ʻApplicationContext` (DI container).

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

When using MockMvc on JUnit 5, add hamcrest-core to the dependent library because the component that verifies the execution result uses Hamcrest's Matcher mechanism.

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

@SpringJUnitConfigTry:point_right:

@SpringJUnitConfigIs a synthetic annotation to indicate that you are using the Spring TestContext Framework on Junit 5(@ExtendWith(SpringExtension.class) + @ContextConfiguration)And if necessary@ContextConfigurationYou can specify the attributes provided by.

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 // ★★★ Specify instead of @ExtendWith (SpringExtension.class)
class SpringJUnitConfigOnJunit5Test {

	@Autowired private ApplicationContext applicationContext;

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

	@Configuration
	static class LocalTestContext {}

}

If you want to change the default behavior ...

When using the JavaConfig class provided for testing


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

With a feeling like@SpringJUnitConfigYou can use the attributes of.

@SpringJUnitWebConfigTry:point_right:

@SpringJUnitWebConfigIs@SpringJUnitConfigIn the WEB version of@SpringJUnitConfigThe difference with@WebAppConfigurationHas been granted/Only the difference is not.

actually@SpringJUnitWebConfigTo try, you need to add some dependent libraries. In particular····

is. This area is necessary when creating or running the application to be tested, so I think that it is a part that you do not usually have to worry about.

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>

After adding the library,@SpringJUnitWebConfigCreate a test case class with.

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 // ★★★ Specify instead of @ExtendWith (SpringExtension.class)
class SpringJUnitWebConfigOnJunit5Test {

	@Autowired private ApplicationContext applicationContext;

 // You can inject Mock = @WebAppConfiguration is working!
	@Autowired private MockServletContext mockServletContext;
	@Autowired private MockHttpSession mockHttpSession;
	@Autowired private MockHttpServletRequest mockRequest;

	@Test
	void defaultContextTest() {
 // ApplicationContext also uses web classes = @WebAppConfiguration is working!
		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 {}

}

@EnabledIfWhen@DisabledIfTry:point_right:

@EnabledIf"Satisfies the specified conditions (Expression result specified by SpEL istrueIf you want to run the test ",@DisabledIfIs an annotation that indicates "skip the test when the condition is met" and can be specified at both the class level and the method level.

In this entry, when there is a test to be performed and a test to be skipped if the OS is Mac, we will use this annotation to control the execution of the test.

package com.example.spring5testdemo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.junit.jupiter.DisabledIf;
import org.springframework.test.context.junit.jupiter.EnabledIf;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;

@SpringJUnitConfig
class XxxIfOnJunit5Test {

	@Test
	@EnabledIf("#{systemProperties['os.name'].toLowerCase().contains('mac')}")
	void enableOnMac() {
 // Tested when OS is Mac
		// ...
	}

	@Test
	@DisabledIf("#{systemProperties['os.name'].toLowerCase().contains('mac')}")
	void disableOnMac() {
 // The test is skipped when the OS is Mac (= the test is performed when the OS is other than Mac)
		// ...
	}

	@Configuration
	static class LocalTestContext {}

}
$ mvn test
...
Tests run: 2, Failures: 0, Errors: 0, Skipped: 1, Time elapsed: 0.128 sec - in com.example.spring5testdemo.XxxIfOnJunit5Test
...

Conditions to use only in specific test cases(expression)Then you can write it in ad hoc as above, but if you need to specify the same conditions in multiple tests,@EnabledIfOr@DisabledIfIt is better to create a synthetic annotation with the meta annotation.

Annotations to enable testing on Mac


package com.example.spring5testdemo;

import org.springframework.test.context.junit.jupiter.EnabledIf;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@EnabledIf("#{systemProperties['os.name'].toLowerCase().contains('mac')}")
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface EnabledOnMac {
}

Annotation to skip test on 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 {
}

Test code


@Test
 @EnabledOnMac // ★★★ Specify the created synthetic annotation and share the activation condition
void enableOnMac() {
	// ...
}

@Test
 @DisabledOnMac // ★★★ Specify the created synthetic annotation and share the skip condition
void disableOnMac() {
	// ...
}

#Can run tests using Spring TestContext Framework in parallel:thumbsup:

[SPR-5863]:SpringTestContextFramework(TCF)Allowsyoutoruntestsusinginparallel.IwantedtotryitwithJUnit5,but...Icouldn't"quickly"createanenvironmentforparallelexecution,soIdecidedtotryitwithJUnit4onlyhere...:sweat_smile:(Notbad) Maven-surefire-You need to temporarily exclude the library for JUnit 5 from the plugin's dependent libraries.

Note:

I will briefly introduce it in this entry, but for restrictions and precautions during parallel execution, see "Spring Framework Reference"Please refer to the.

pom.xml


<!-- ... -->
</dependencies>
 <!-★★★ Added JUnit 4->
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
  </dependency>
</dependencies>
<!-- ... -->
<build>
  <plugins>
    <plugin>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>2.19.1</version>
 <!-★★★ Added parallel execution setting (Example: Execute test case with 3 threads on 1JMV)->
      <configuration>
        <parallel>methods</parallel>
        <threadCount>3</threadCount>
      </configuration>
    </plugin>
  </plugins>
</build>
<!-- ... -->

Prepare three test methods in the test class.

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

}

When this test case is executed, the following log (excerpt) will be output on the console.

$ mvn test -Dtest=ParallelTest
...
★★★★three★★★★pool-1-thread-3 :com.example.spring5testdemo.ParallelTest@7ff7cced
★★★★three★★★★pool-1-thread-3 :org.springframework.web.context.support.GenericWebApplicationContext@128169a9: startup date [Sun May 21 17:49:56 JST 2017]; root of context hierarchy
17:49:57.966 [pool-1-thread-3] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'foo'
★★★★three★★★★pool-1-thread-3 :com.example.spring5testdemo.ParallelTest$Foo@11a551ce
★★★★three★★★★pool-1-thread-3 :org.springframework.mock.web.MockHttpServletRequest@2695d62a
...
★★★★two★★★★pool-1-thread-2 :com.example.spring5testdemo.ParallelTest@1fad7c69
★★★★two★★★★pool-1-thread-2 :org.springframework.web.context.support.GenericWebApplicationContext@128169a9: startup date [Sun May 21 17:49:56 JST 2017]; root of context hierarchy
17:49:57.966 [pool-1-thread-2] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'foo'
★★★★two★★★★pool-1-thread-2 :com.example.spring5testdemo.ParallelTest$Foo@11a551ce
★★★★two★★★★pool-1-thread-2 :org.springframework.mock.web.MockHttpServletRequest@7927bef5
...
★★★★one★★★★pool-1-thread-1 :com.example.spring5testdemo.ParallelTest@3693321f
★★★★one★★★★pool-1-thread-1 :org.springframework.web.context.support.GenericWebApplicationContext@128169a9: startup date [Sun May 21 17:49:56 JST 2017]; root of context hierarchy
17:49:57.966 [pool-1-thread-1] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'foo'
★★★★one★★★★pool-1-thread-1 :com.example.spring5testdemo.ParallelTest$Foo@11a551ce
★★★★one★★★★pool-1-thread-1 :org.springframework.mock.web.MockHttpServletRequest@5950ee9d
...
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.013 sec - in com.example.spring5testdemo.ParallelTest
...

What you can see from this log ...

*Three test case methods are running in parallel on different threads *An instance of the test case class is created for each test case method *InjectingApplicationContextIs shared in each test case *The injected Mock object is instantiated for each test case

about it. The point is ...ApplicationContextWill be shared. In parallel execution, tests are executed at the same time, so if there is a test case that updates the state of the object managed by the DI container, it may affect the execution result of another test case. Also, although not limited to tests using TCF, parallel execution of tests that access external resources (databases, files, etc.) may not produce the expected results. In this way ... Is it possible to execute in parallel? It depends on the creation of applications and test cases, so be aware that if you easily adopt parallel execution, unexpected errors may occur.

#Added callback methods that are called just before and immediately after running the test:thumbsup:

[SPR-4365]:TestExecutionListenerCallbackmethodsthatarecalledontheinterfacejustbeforeandafterrunningthetest(beforeTestExecutionWhenafterTestExecution)Will be added.

In this entry, JUnit 5 is used, and "pre-processing and post-processing provided by the mechanism of JUnit itself" and "Spring TestContext Framework"(TCF)I will introduce the order of "pre-processing and post-processing provided by the mechanism of".

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) // ★★★ Specify the implementation class of TestExecutionListener
class TestExecutionListenerTest {

	// ------------------------------------
 // Pre-processing and post-processing provided by the mechanism of JUnit itself
	// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
	@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");
	}
	// ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
 // Pre-processing and post-processing provided by the mechanism of JUnit itself
	// ------------------------------------

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

	// ------------------------------------------------------------
 // Pre-processing and post-processing provided by the mechanism of 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 // ★★★ Methods added in 5.0
		public void beforeTestExecution(TestContext testContext) throws Exception {
			System.out.println(testContext.getTestMethod().getName() + "-beforeTestExecution");
		}

 @Override // ★★★ Methods added in 5.0
		public void afterTestExecution(TestContext testContext) throws Exception {
			System.out.println(testContext.getTestMethod().getName() + "-afterTestExecution");
		}

		@Override
		public void afterTestMethod(TestContext testContext) throws Exception {
			System.out.println(testContext.getTestMethod().getName() + "-afterTestMethod");
		}

		@Override
		public void afterTestClass(TestContext testContext) throws Exception {
			System.out.println("afterTestClass");
		}

	}

	@Configuration
	static class LocalTestContext {}

}

Running the above test will produce console output similar to the following:

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 ← Methods added in 5.0
test2
 test2-afterTestExecution ← Methods added in 5.0
test2-afterEach
test2-afterTestMethod
prepareTestInstance
test1-beforeTestMethod
test1-beforeEach
 test1-beforeTestExecution ← Methods added in 5.0
test1
 test1-afterTestExecution ← Methods added in 5.0
test1-afterEach
test1-afterTestMethod
afterAll
afterTestClass

By the way ... TCF provides it by defaultTestExecutionListenerIf you want to use it with the implementation class of, you need to specify the merge mode. (Probably, there are many cases where you want to use it together)

@SpringJUnitConfig
@TestExecutionListeners(listeners = TestExecutionListenerTest.MyTestExecutionListener.class,
 mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) // Change mergeMode (it will be replaced if it is left as default)
class TestExecutionListenerTest {
	// ...
}

MockHttpServletRequestA method to get the request BODY is added to:thumbsup:

[SPR-14717]:MockHttpServletRequestMethodtoaccesstherequestBODY(getContentAsByteArrayWhengetContentAsString)Will be added. This correspondence will be explained later in "MockMvcRequest BODY is output in the test result at the time of use:thumbsup:」を対応するために行われたものです。正直・・・このメソッドを個別に使うこWhenはほWhenんどないWhen思うので、サンプルを交えた説明は割愛させていただきます。

MockMvcRequest BODY is output in the test result at the time of use:thumbsup:

[SPR-14717]:MockMvcWhenoutputtingthetestresultatthetimeofusetotheconsoleorlog(MockMvcResultHandlersofprintOrlogWhenusingthemethod)In addition, the request BODY will also be output.

Let's see specifically "what" and "how" are output. Before that ...MockMvcTo use spring-You need to add webmvc to the dependent libraries.

pom.xml


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

After adding the dependent libraries, create a controller and test case for testing.

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") // ★★★ ← This will be output
			.param("foo", "baz")
		).andExpect(
			status().isOk()
		).andExpect(
			result -> Assertions.assertEquals("[baz, bar]", result.getResponse().getContentAsString())
 // content (). string ("[baz, bar]") // If Hamcrest is on the classpath, you can write it like this
		).andDo(
 print () // console output
		).andDo(
 log () // Log output
		);
	}

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

}

When you execute the created test, the test execution result is output to the console or log file.

print()Output result of(console)


MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /post
       Parameters = {foo=[baz, bar]}
          Headers = {Content-Type=[application/x-www-form-urlencoded;charset=UTF-8]}
 Body = foo = bar ★★★ ← This is output from 5.0
    Session Attrs = {}

Handler:
             Type = com.example.spring5testdemo.MvcMockTest$WelcomeController
           Method = java.lang.String com.example.spring5testdemo.MvcMockTest$WelcomeRestController.post(java.util.List<java.lang.String>)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {Content-Type=[text/plain;charset=ISO-8859-1], Content-Length=[10]}
     Content type = text/plain;charset=ISO-8859-1
             Body = [baz, bar]
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

log()Output result (console, log file, etc.)


14:36:46.179 [main] DEBUG org.springframework.test.web.servlet.result - MvcResult details:

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /post
       Parameters = {foo=[baz, bar]}
          Headers = {Content-Type=[application/x-www-form-urlencoded;charset=UTF-8]}
 Body = foo = bar ★★★ ← This is output from 5.0
    Session Attrs = {}

Handler:
             Type = com.example.spring5testdemo.MvcMockTest$WelcomeController
           Method = java.lang.String com.example.spring5testdemo.MvcMockTest$WelcomeRestController.post(java.util.List<java.lang.String>)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {Content-Type=[text/plain;charset=ISO-8859-1], Content-Length=[10]}
     Content type = text/plain;charset=ISO-8859-1
             Body = [baz, bar]
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

By the way ...print()Orlog()If you want to apply to all test cases,AbstractMockMvcBuilderIs implemented inalwaysDoLet's use the method.

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

MockMvcURI template can be used when verifying "redirect destination URL" and "forward destination URL" at the time of use:thumbsup:

[SPR-14790]:MockMvcWhenverifyingthe"redirectdestinationURL"and"forwarddestinationURL"atthetimeofuse,itbecomespossibletospecifyaURItemplatefortheexpectedvalue.(Personally,Idon'tthinkIhavemuchchancetousethe"forwarddestinationURL".)

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 verification at the time of redirect
		);
	}

	@Test
	void testForward() throws Exception {
		mockMvc.perform(get("/forward/{id}", 1))
			.andExpect(
				status().isOk()
			).andExpect(
 forwardedUrl ("/ transition / forward / {id}", 1) // ★★★ URL verification at the time of forward
		);
	}

	@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; // Personally, I basically don't write this kind of code ... (because it's a sample ...)
		}
	}

}

#Support version of XMLUnit is 2.Become 3

[SPR-14043]:Supportversion2ofXMLUnit,alibrarythatsupportsXMLvalidation.Itwillbe3(Thesamplecodeintroducedinthisentryis2.0.Itworkedevenwith0).Lookingatthechanges2.Verificationmethodfromxseries(assertXxx)Hamcrest instead ofMatcherSeems to be offered now. In Spring TestMockMvcSome components that verify the processing result at the time of use depend on XMLUnit.

If you want to use the functions that depend on XMLUnit, you need to add XMLUnit to the dependent library as follows.

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>") // ★★★ Evaluate as an XML document (= Differences in spaces and line breaks are not treated as differences)
		);
	}

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

}

Note:

The actual verification process isXmlExpectationsHelperBecause it is delegated toMockMvcIt is possible to perform the same verification in places other than the above.

#Summary

This time, I introduced the main changes related to Test. After all ... JUnit 5 support is the biggest feature. JUnit 5 refers to JUnit 4 as JUnit Vintage(=Not backward expression)I personally like it. It's attractive not only to talk about names, but also to be able to execute "test cases written in JUnit 5" and "test cases written in JUnit 4" at the same time. (You can transfer past deliverables as they are !! = If you have the spare capacity, you can convert it to JUnit 5 at the code level !!). Maven(maven-surefire-plugin)Then ...

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>
 <!-★★★ ↓ If you add this, you can test test cases written in JUnit 5 and JUnit 4 at the same time->
    <dependency>
      <groupId>org.junit.vintage</groupId>
      <artifactId>junit-vintage-engine</artifactId>
      <version>4.12.0-M4</version>
    </dependency>
  </dependencies>
</plugin>

It's OK if you make it feel like that.

I have derailed from the story of Spring Framework:sweat_smile:... Testing is a very important element in application development, and the Spring Framework also provides a wealth of support functions for creating test code. (To keep the schedule in the near future) "Because I don't have time, I will postpone the test (= insist that the operation check is a test)!" There are people, but in the end no one will get it, so review (adjust) the schedule and make sure you have the test code in place. When creating an application using Spring, "Spring Framework Reference(Test edition)Werecommendthatyouread".(Thereisquitealot,butw) Next time, I will introduce the Web framework (WebFlux) of Reactive Programming Model.

#Appendix: Spring Boot 2.How to use JUnit 5 with 0

Here, Spring Boot 2.0 for JUnit 5(+JUnit 4)I will introduce how to use (coexist). Basically, just apply what was described in this entry to your Spring Boot application.

*Creating a Spring Boot project

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

*Test case class for JUnit 5(Empty test case)Creation

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

}

*Run the test

$ ./mvnw test
/usr/local/apps/test-demo
[INFO] Scanning for projects...
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] Building test-demo 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ test-demo ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ test-demo ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ test-demo ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /usr/local/apps/test-demo/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ test-demo ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-surefire-plugin:2.19.1:test (default-test) @ test-demo ---

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
19:23:22.969 [main] DEBUG org.springframework.test.context.junit4.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class com.example.testdemo.TestDemoApplicationTests]
19:23:22.973 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
19:23:22.978 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
19:23:22.990 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.example.testdemo.TestDemoApplicationTests] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
19:23:22.999 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.example.testdemo.TestDemoApplicationTests], using SpringBootContextLoader
19:23:23.002 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.example.testdemo.TestDemoApplicationTests]: class path resource [com/example/testdemo/TestDemoApplicationTests-context.xml] does not exist
19:23:23.002 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.example.testdemo.TestDemoApplicationTests]: class path resource [com/example/testdemo/TestDemoApplicationTestsContext.groovy] does not exist
19:23:23.002 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.example.testdemo.TestDemoApplicationTests]: no resource found for suffixes {-context.xml, Context.groovy}.
19:23:23.003 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.example.testdemo.TestDemoApplicationTests]: TestDemoApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
19:23:23.049 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.055 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
19:23:23.055 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
19:23:23.056 [main] DEBUG org.springframework.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
19:23:23.066 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Resolved classpath location [com/example/testdemo/] to resources [URL [file:/usr/local/apps/test-demo/target/test-classes/com/example/testdemo/], URL [file:/usr/local/apps/test-demo/target/classes/com/example/testdemo/]]
19:23:23.067 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Looking for matching resources in directory tree [/usr/local/apps/test-demo/target/test-classes/com/example/testdemo]
19:23:23.067 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Searching directory [/usr/local/apps/test-demo/target/test-classes/com/example/testdemo] for files matching pattern [/usr/local/apps/test-demo/target/test-classes/com/example/testdemo/*.class]
19:23:23.069 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Looking for matching resources in directory tree [/usr/local/apps/test-demo/target/classes/com/example/testdemo]
19:23:23.069 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Searching directory [/usr/local/apps/test-demo/target/classes/com/example/testdemo] for files matching pattern [/usr/local/apps/test-demo/target/classes/com/example/testdemo/*.class]
19:23:23.069 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Resolved location pattern [classpath*:com/example/testdemo/*.class] to resources [file [/usr/local/apps/test-demo/target/test-classes/com/example/testdemo/TestDemoApplicationTests.class], file [/usr/local/apps/test-demo/target/test-classes/com/example/testdemo/TestDemoApplicationUsingJUnit5Tests.class], file [/usr/local/apps/test-demo/target/classes/com/example/testdemo/TestDemoApplication.class]]
19:23:23.113 [main] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [/usr/local/apps/test-demo/target/classes/com/example/testdemo/TestDemoApplication.class]
19:23:23.114 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.example.testdemo.TestDemoApplication for test class com.example.testdemo.TestDemoApplicationTests
19:23:23.203 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.example.testdemo.TestDemoApplicationTests]: using defaults.
19:23:23.203 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
19:23:23.209 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
19:23:23.209 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
19:23:23.212 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
19:23:23.212 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@d35dea7, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@7770f470, org.springframework.test.context.support.DirtiesContextTestExecutionListener@5e5d171f, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@24313fcc, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@7d20d0b, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@77f1baf5, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@41a2befb, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@6c40365c, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@7bedc48a]
19:23:23.214 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.214 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.example.testdemo.TestDemoApplicationTests]
Running com.example.testdemo.TestDemoApplicationTests
19:23:23.244 [main] DEBUG org.springframework.test.context.junit4.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class com.example.testdemo.TestDemoApplicationTests]
19:23:23.245 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
19:23:23.245 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
19:23:23.245 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.example.testdemo.TestDemoApplicationTests] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
19:23:23.245 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.example.testdemo.TestDemoApplicationTests], using SpringBootContextLoader
19:23:23.246 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.example.testdemo.TestDemoApplicationTests]: class path resource [com/example/testdemo/TestDemoApplicationTests-context.xml] does not exist
19:23:23.246 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.example.testdemo.TestDemoApplicationTests]: class path resource [com/example/testdemo/TestDemoApplicationTestsContext.groovy] does not exist
19:23:23.246 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.example.testdemo.TestDemoApplicationTests]: no resource found for suffixes {-context.xml, Context.groovy}.
19:23:23.246 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.example.testdemo.TestDemoApplicationTests]: TestDemoApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
19:23:23.249 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.249 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
19:23:23.250 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
19:23:23.250 [main] DEBUG org.springframework.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
19:23:23.251 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.example.testdemo.TestDemoApplication for test class com.example.testdemo.TestDemoApplicationTests
19:23:23.258 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.example.testdemo.TestDemoApplicationTests]: using defaults.
19:23:23.258 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
19:23:23.258 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
19:23:23.259 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
19:23:23.260 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
19:23:23.260 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@50caa560, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@2a266d09, org.springframework.test.context.support.DirtiesContextTestExecutionListener@5ab9e72c, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@186f8716, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@1d8bd0de, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@45ca843, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@11c9af63, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@757acd7b, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@36b4fe2a]
19:23:23.260 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.260 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.294 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.294 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.295 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.295 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.296 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.296 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.299 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@693fe6c9 testClass = TestDemoApplicationTests, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration@34f5090e testClass = TestDemoApplicationTests, locations = '{}', classes = '{class com.example.testdemo.TestDemoApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@25359ed8, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@80ec1f8, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@709ba3fb], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map[[empty]]], class annotated with @DirtiesContext [false] with mode [null].
19:23:23.299 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.299 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.example.testdemo.TestDemoApplicationTests]
19:23:23.300 [main] DEBUG org.springframework.test.context.support.DependencyInjectionTestExecutionListener - Performing dependency injection for test context [[DefaultTestContext@693fe6c9 testClass = TestDemoApplicationTests, testInstance = com.example.testdemo.TestDemoApplicationTests@22e357dc, testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration@34f5090e testClass = TestDemoApplicationTests, locations = '{}', classes = '{class com.example.testdemo.TestDemoApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@25359ed8, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@80ec1f8, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@709ba3fb], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map[[empty]]]].
19:23:23.315 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
19:23:23.316 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
19:23:23.316 [main] DEBUG org.springframework.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
19:23:23.320 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=-1}
19:23:23.320 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [Inlined Test Properties] PropertySource with highest search precedence
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
 ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
  \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
   '  |____| .__|_| |_|_| |_\__, | / / / /
  =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::             (v2.0.0.M1)
2017-05-21 19:23:23.786  INFO 70579 --- [           main] c.e.testdemo.TestDemoApplicationTests    : Starting TestDemoApplicationTests on Kazuki-no-MacBook-Pro.local with PID 70579 (started by shimizukazuki in /usr/local/apps/test-demo)
2017-05-21 19:23:23.788  INFO 70579 --- [           main] c.e.testdemo.TestDemoApplicationTests    : No active profile set, falling back to default profiles: default
2017-05-21 19:23:23.807  INFO 70579 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@387a8303: startup date [Sun May 21 19:23:23 JST 2017]; root of context hierarchy
2017-05-21 19:23:24.135  INFO 70579 --- [           main] c.e.testdemo.TestDemoApplicationTests    : Started TestDemoApplicationTests in 0.81 seconds (JVM running for 1.56)
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.973 sec - in com.example.testdemo.TestDemoApplicationTests
Running com.example.testdemo.TestDemoApplicationUsingJUnit5Tests
2017-05-21 19:23:24.242  INFO 70579 --- [           main] .b.t.c.SpringBootTestContextBootstrapper : Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.example.testdemo.TestDemoApplicationUsingJUnit5Tests], using SpringBootContextLoader
2017-05-21 19:23:24.242  INFO 70579 --- [           main] o.s.t.c.support.AbstractContextLoader    : Could not detect default resource locations for test class [com.example.testdemo.TestDemoApplicationUsingJUnit5Tests]: no resource found for suffixes {-context.xml, Context.groovy}.
2017-05-21 19:23:24.242  INFO 70579 --- [           main] t.c.s.AnnotationConfigContextLoaderUtils : Could not detect default configuration classes for test class [com.example.testdemo.TestDemoApplicationUsingJUnit5Tests]: TestDemoApplicationUsingJUnit5Tests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
2017-05-21 19:23:24.244  INFO 70579 --- [           main] .b.t.c.SpringBootTestContextBootstrapper : Found @SpringBootConfiguration com.example.testdemo.TestDemoApplication for test class com.example.testdemo.TestDemoApplicationUsingJUnit5Tests
2017-05-21 19:23:24.247  INFO 70579 --- [           main] .b.t.c.SpringBootTestContextBootstrapper : Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
2017-05-21 19:23:24.247  INFO 70579 --- [           main] .b.t.c.SpringBootTestContextBootstrapper : Could not instantiate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
2017-05-21 19:23:24.247  INFO 70579 --- [           main] .b.t.c.SpringBootTestContextBootstrapper : Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
2017-05-21 19:23:24.247  INFO 70579 --- [           main] .b.t.c.SpringBootTestContextBootstrapper : Could not instantiate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
2017-05-21 19:23:24.248  INFO 70579 --- [           main] .b.t.c.SpringBootTestContextBootstrapper : Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@665e9289, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@7d3430a7, org.springframework.test.context.support.DirtiesContextTestExecutionListener@6f603e89, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@2756c0a7, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@350ec41e, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@69637b10, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@71984c3, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@165b2f7f, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@5536379e]
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.016 sec - in com.example.testdemo.TestDemoApplicationUsingJUnit5Tests
2017-05-21 19:23:24.258  INFO 70579 --- [       Thread-2] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@387a8303: startup date [Sun May 21 19:23:23 JST 2017]; root of context hierarchy

Results :

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.126 s
[INFO] Finished at: 2017-05-21T19:23:24+09:00
[INFO] Final Memory: 20M/347M
[INFO] ------------------------------------------------------------------------

Recommended Posts

Major changes related to Spring Framework 5.0 Test
Major changes related to Spring Framework 5.0 Web MVC
Major changes related to Spring Framework 5.0 DI container
Spring Framework 5.0 Summary of major changes
Major changes in Spring Framework 5.0 core functionality
Major changes in Spring Boot 1.5
How to unit test Spring AOP
Test Spring framework controller with Junit
Changes when migrating from Spring Boot 1.5 to Spring Boot 2.0
Changes when migrating from Spring Boot 2.0 to Spring Boot 2.2
I tried to link JavaFX and Spring Framework.
How to write a unit test for Spring Boot 2
How to use Struts2 * Spring Framework (Spring plugin) June 2017 Version
How to test file upload screen in Spring + Selenium
[Spring Framework] Configuration split
Spring Framework multilingual support
Changes from Java 8 to Java 11
1. Start Spring framework from 1
Spring Framework Summary-About DI
Introduction to RSpec 1. Test, RSpec
Play Framework studying test
Spring Framework 5.2.0 --Vary header duplication due to CORS handling change