从命令行运行 gradle 时如何执行和显示友好的测试输出

Posted

技术标签:

【中文标题】从命令行运行 gradle 时如何执行和显示友好的测试输出【英文标题】:how execute and show friendly tests output when running gradle from command line 【发布时间】:2020-08-11 06:51:42 【问题描述】:

我可以从 IntelliJ IDEA 轻松运行我的项目测试,但我很难运行它们并查看从命令行运行的结果。

我阅读了一些建议,似乎技巧部分在这里结束了

tasks.test 
    useJUnitPlatform()


tasks.withType<Test> 
    this.testLogging 
        this.showStandardStreams = true
    

正如您从下面的图片中看到的那样,所有测试都已运行,我可以在 IntelliJ 中看到结果

不过,当我在同一个项目中从 Windows 命令行尝试时,我得到了

C:\WSs\KotlinGradleIntelliJ\jokenpo>gradlew 测试

> Task :test

JokenpoApplicationTests STANDARD_OUT
    13:19:28.436 [Test worker] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
    13:19:28.452 [Test worker] 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)]
    13:19:28.467 [Test worker] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.mycomp.jokenpo.JokenpoApplicationTests] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
    13:19:28.483 [Test worker] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.mycomp.jokenpo.JokenpoApplicationTests], using SpringBootContextLoader
    13:19:28.498 [Test worker] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.mycomp.jokenpo.JokenpoApplicationTests]: class path resource [com/mycomp/jokenpo/JokenpoApplicationTests-context.xml] does not exist
    13:19:28.498 [Test worker] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.mycomp.jokenpo.JokenpoApplicationTests]: class path resource [com/mycomp/jokenpo/JokenpoApplicationTestsContext.groovy] does not exist
    13:19:28.498 [Test worker] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.mycomp.jokenpo.JokenpoApplicationTests]: no resource found for suffixes -context.xml, Context.groovy.
    13:19:28.498 [Test worker] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.mycomp.jokenpo.JokenpoApplicationTests]: JokenpoApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
    13:19:28.552 [Test worker] 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.mycomp.jokenpo.JokenpoApplicationTests]
    13:19:28.621 [Test worker] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [C:\WSs\KotlinGradleIntelliJ\jokenpo\build\classes\kotlin\main\com\mycomp\jokenpo\JokenpoApplication.class]
    13:19:28.621 [Test worker] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.mycomp.jokenpo.JokenpoApplication for test class com.mycomp.jokenpo.JokenpoApplicationTests
    13:19:28.738 [Test worker] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.mycomp.jokenpo.JokenpoApplicationTests]: using defaults.
    13:19:28.739 [Test worker] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [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.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, 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, org.springframework.test.context.event.EventPublishingTestExecutionListener]
    13:19:28.757 [Test worker] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@1f9e5479, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@7f837ef0, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@75d05b, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@532b090b, org.springframework.test.context.support.DirtiesContextTestExecutionListener@3efba28b, org.springframework.test.context.transaction.TransactionalTestExecutionListener@5a6b3f5a, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@7432cb44, org.springframework.test.context.event.EventPublishingTestExecutionListener@7f5ae798, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@1cd6ed02, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@1f44802d, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@7d4e106a, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@55004e7c, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@7e951723]
    13:19:28.762 [Test worker] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@7d4abcae testClass = JokenpoApplicationTests, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@d073212 testClass = JokenpoApplicationTests, locations = '', classes = 'class com.mycomp.jokenpo.JokenpoApplication', contextInitializerClasses = '[]', activeProfiles = '', propertySourceLocations = '', propertySourceProperties = 'org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=0', contextCustomizers = set[org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@4b3fa0b3, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@1a515c84, [ImportsContextCustomizer@672ec1ca key = [org.springframework.boot.test.autoconfigure.web.servlet.MockMvcAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebClientAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebDriverAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcSecurityConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@51dd20fd, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@1a85aac8, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@e2f4006e, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@9eb94ec], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> false]], class annotated with @DirtiesContext [false] with mode [null].
    13:19:28.784 [Test worker] 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=0

      .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::        (v2.2.6.RELEASE)

    2020-04-27 13:19:29.222  INFO 13608 --- [    Test worker] c.m.jokenpo.JokenpoApplicationTests      : Starting JokenpoApplicationTests on SPANOT149 with PID 13608 (started by Cast in C:\WSs\KotlinGradleIntelliJ\jokenpo)
    2020-04-27 13:19:29.222  INFO 13608 --- [    Test worker] c.m.jokenpo.JokenpoApplicationTests      : No active profile set, falling back to default profiles: default
    2020-04-27 13:19:30.008  INFO 13608 --- [    Test worker] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
    2020-04-27 13:19:30.070  INFO 13608 --- [    Test worker] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 64ms. Found 1 JPA repository interfaces.
    2020-04-27 13:19:31.402  INFO 13608 --- [    Test worker] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 0 (http)
    2020-04-27 13:19:31.424  INFO 13608 --- [    Test worker] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
    2020-04-27 13:19:31.424  INFO 13608 --- [    Test worker] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.33]
    2020-04-27 13:19:31.595  INFO 13608 --- [    Test worker] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
    2020-04-27 13:19:31.595  INFO 13608 --- [    Test worker] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2343 ms
    2020-04-27 13:19:31.675  INFO 13608 --- [    Test worker] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
    2020-04-27 13:19:31.916  INFO 13608 --- [    Test worker] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
    2020-04-27 13:19:31.916  INFO 13608 --- [    Test worker] o.s.b.a.h2.H2ConsoleAutoConfiguration    : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:testdb'
    2020-04-27 13:19:32.218  INFO 13608 --- [    Test worker] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
    2020-04-27 13:19:32.301  INFO 13608 --- [    Test worker] org.hibernate.Version                    : HHH000412: Hibernate ORM core version 5.4.12.Final
    2020-04-27 13:19:32.382  INFO 13608 --- [    Test worker] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations 5.1.0.Final
    2020-04-27 13:19:32.533  INFO 13608 --- [    Test worker] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
    2020-04-27 13:19:33.002  INFO 13608 --- [    Test worker] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
    2020-04-27 13:19:33.018  INFO 13608 --- [    Test worker] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default
    2020-04-27 13:19:33.202  WARN 13608 --- [    Test worker] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
    2020-04-27 13:19:33.487  INFO 13608 --- [    Test worker] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
    2020-04-27 13:19:33.836  INFO 13608 --- [    Test worker] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring TestDispatcherServlet ''
    2020-04-27 13:19:33.836  INFO 13608 --- [    Test worker] o.s.t.web.servlet.TestDispatcherServlet  : Initializing Servlet ''
    2020-04-27 13:19:33.851  INFO 13608 --- [    Test worker] o.s.t.web.servlet.TestDispatcherServlet  : Completed initialization in 15 ms
    2020-04-27 13:19:33.904  INFO 13608 --- [    Test worker] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 56309 (http) with context path ''
    2020-04-27 13:19:33.904  INFO 13608 --- [    Test worker] c.m.jokenpo.JokenpoApplicationTests      : Started JokenpoApplicationTests in 5.107 seconds (JVM running for 7.245)

UserServiceTest STANDARD_OUT
    2020-04-27 13:19:34.605  INFO 13608 --- [    Test worker] .b.t.c.SpringBootTestContextBootstrapper : Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.mycomp.jokenpo.UserServiceTest], using SpringBootContextLoader
    2020-04-27 13:19:34.605  INFO 13608 --- [    Test worker] o.s.t.c.support.AbstractContextLoader    : Could not detect default resource locations for test class [com.mycomp.jokenpo.UserServiceTest]: no resource found for suffixes -context.xml, Context.groovy.
    2020-04-27 13:19:34.605  INFO 13608 --- [    Test worker] t.c.s.AnnotationConfigContextLoaderUtils : Could not detect default configuration classes for test class [com.mycomp.jokenpo.UserServiceTest]: UserServiceTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
    2020-04-27 13:19:34.605  INFO 13608 --- [    Test worker] .b.t.c.SpringBootTestContextBootstrapper : Found @SpringBootConfiguration com.mycomp.jokenpo.JokenpoApplication for test class com.mycomp.jokenpo.UserServiceTest
    2020-04-27 13:19:34.605  INFO 13608 --- [    Test worker] .b.t.c.SpringBootTestContextBootstrapper : Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [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.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, 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, org.springframework.test.context.event.EventPublishingTestExecutionListener]
    2020-04-27 13:19:34.605  INFO 13608 --- [    Test worker] .b.t.c.SpringBootTestContextBootstrapper : Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@2401a061, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@7ef022b4, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@5970e47d, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@3a26795d, org.springframework.test.context.support.DirtiesContextTestExecutionListener@130dd4d0, org.springframework.test.context.transaction.TransactionalTestExecutionListener@6c97b187, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@321ae364, org.springframework.test.context.event.EventPublishingTestExecutionListener@3bff88eb, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@46296010, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@17e3eadb, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@72872a80, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@35784ceb, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@38dc83b4]

      .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::        (v2.2.6.RELEASE)

    2020-04-27 13:19:34.653  INFO 13608 --- [    Test worker] com.mycomp.jokenpo.UserServiceTest       : Starting UserServiceTest on SPANOT149 with PID 13608 (started by Cast in C:\WSs\KotlinGradleIntelliJ\jokenpo)
    2020-04-27 13:19:34.653  INFO 13608 --- [    Test worker] com.mycomp.jokenpo.UserServiceTest       : No active profile set, falling back to default profiles: default
    2020-04-27 13:19:34.858  INFO 13608 --- [    Test worker] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
    2020-04-27 13:19:34.858  INFO 13608 --- [    Test worker] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 13ms. Found 1 JPA repository interfaces.
    2020-04-27 13:19:35.005  INFO 13608 --- [    Test worker] com.zaxxer.hikari.HikariDataSource       : HikariPool-2 - Starting...
    2020-04-27 13:19:35.005  INFO 13608 --- [    Test worker] com.zaxxer.hikari.HikariDataSource       : HikariPool-2 - Start completed.
    2020-04-27 13:19:35.037  INFO 13608 --- [    Test worker] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
    2020-04-27 13:19:35.037  INFO 13608 --- [    Test worker] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
    2020-04-27 13:19:35.081  INFO 13608 --- [    Test worker] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
    2020-04-27 13:19:35.081  INFO 13608 --- [    Test worker] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
    2020-04-27 13:19:35.378  WARN 13608 --- [    Test worker] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
    2020-04-27 13:19:35.500  INFO 13608 --- [    Test worker] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
    2020-04-27 13:19:35.679  INFO 13608 --- [    Test worker] o.s.b.a.h2.H2ConsoleAutoConfiguration    : H2 console available at '/h2-console'. Database available at 'jdbc:h2:mem:testdb'
    2020-04-27 13:19:35.738  INFO 13608 --- [    Test worker] com.mycomp.jokenpo.UserServiceTest       : Started UserServiceTest in 1.11 seconds (JVM running for 9.072)
2020-04-27 13:19:35.754  INFO 13608 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
2020-04-27 13:19:35.755  INFO 13608 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
2020-04-27 13:19:35.755  INFO 13608 --- [extShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-04-27 13:19:35.756  INFO 13608 --- [extShutdownHook] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477: Starting delayed evictData of schema as part of SessionFactory shut-down'
2020-04-27 13:19:35.756  INFO 13608 --- [extShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-04-27 13:19:35.756  INFO 13608 --- [extShutdownHook] .SchemaDropperImpl$DelayedDropActionImpl : HHH000477: Starting delayed evictData of schema as part of SessionFactory shut-down'
2020-04-27 13:19:35.759  INFO 13608 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-2 - Shutdown initiated...
2020-04-27 13:19:35.759  INFO 13608 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2020-04-27 13:19:35.765  INFO 13608 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.
2020-04-27 13:19:35.765  INFO 13608 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-2 - Shutdown completed.

BUILD SUCCESSFUL in 14s
4 actionable tasks: 1 executed, 3 up-to-date
C:\WSs\KotlinGradleIntelliJ\jokenpo> 

build.gradle.kts

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins 
    id("org.springframework.boot") version "2.2.6.RELEASE"
    id("io.spring.dependency-management") version "1.0.9.RELEASE"
    kotlin("jvm") version "1.3.71"
    kotlin("plugin.spring") version "1.3.71"
    kotlin("plugin.jpa") version "1.3.71"


group = "com.mycomp"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_1_8

val developmentOnly by configurations.creating
configurations 
    runtimeClasspath 
        extendsFrom(developmentOnly)
    


repositories 
    mavenCentral()


dependencies 
    implementation("org.springframework.boot:spring-boot-starter-data-jpa")
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    developmentOnly("org.springframework.boot:spring-boot-devtools")
    runtimeOnly("com.h2database:h2")
    //runtimeOnly("org.hsqldb:hsqldb")
    testImplementation("org.springframework.boot:spring-boot-starter-test") 
        exclude(group = "org.junit.vintage", module = "junit-vintage-engine")
    
    testImplementation ("com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0")


tasks.withType<Test> 
    useJUnitPlatform()


tasks.withType<KotlinCompile> 
    kotlinOptions 
        freeCompilerArgs = listOf("-Xjsr305=strict")
        jvmTarget = "1.8"
    



tasks.test 
    useJUnitPlatform()


tasks.withType<Test> 
    this.testLogging 
        this.showStandardStreams = true
    

测试文件

package com.mycomp.jokenpo

import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.mycomp.jokenpo.enums.PlayType
import com.mycomp.jokenpo.model.User
import com.mycomp.jokenpo.respository.UserRepository
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.junit.jupiter.MockitoExtension
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.http.MediaType
import org.springframework.test.context.junit.jupiter.SpringExtension
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.get
import org.springframework.test.web.servlet.post
import org.springframework.web.util.NestedServletException

@AutoConfigureMockMvc
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ExtendWith(SpringExtension::class, MockitoExtension::class)
class JokenpoApplicationTests 

    @Autowired
    private lateinit var mockMvc: MockMvc

    @MockBean
    lateinit var respository: UserRepository

    @BeforeEach
    fun setup() 
        whenever(respository.save(User(1, "Test", PlayType.LAGARTO))).thenAnswer 
            it.arguments.first()
        
    

    @Test
    fun `Test createUser in the happy path scenario`() 
        val user = User(1, "Test", PlayType.LAGARTO)
        mockMvc.post("/users/") 
            contentType = MediaType.APPLICATION_JSON
            content = jacksonObjectMapper().writeValueAsString(user)
            accept = MediaType.APPLICATION_JSON
        .andExpect 
            status  isOk 
            content  contentType(MediaType.APPLICATION_JSON) 
            content  json(""""id":1,"name":"Test"""") 
        
        //verify(respository, times(1)).save(user)
    

    @Test
    fun `Test negative scenario of createUser`() 
        val user = User(2, "Test", PlayType.LAGARTO)
        assertThrows<NestedServletException> 
            mockMvc.post("/users/") 
                contentType = MediaType.APPLICATION_JSON
                content = jacksonObjectMapper().writeValueAsString(user)
                accept = MediaType.APPLICATION_JSON
            
        
        verify(respository, times(1)).save(user)
    

    @Test
    fun findUser() 
        mockMvc.get("/users?id=99")
                .andExpect 
                    status  isOk 
                
        verify(respository, times(1)).findAll()
    

PS.:如果我尝试“gradle clean test”或使用“gradle test --tests JokenpoApplicationTests”指向文件,我看不到输出有任何变化

如果我的测试被执行,我会感到困惑,但我错过了一些 Gradle 配置来显示结果,甚至最糟糕的是我的测试根本没有执行,我失去了一些基本概念,因为 IntelliJ 自动添加了它并从我的眼睛“隐藏”

【问题讨论】:

@AnimeshSahu 如果您的意思是 IntelliJ 面板,恐怕您不理解我的问题。从 IntelliJ 测试正在运行,我可以很容易地看到结果。我的问题是关于运行并从命令行查看结果 啊,对不起,我的想法正好相反。 【参考方案1】:

使用 Gradle 富控制台时,Gradle 输出的动态部分会报告测试执行情况。这意味着一旦测试完成,该输出就消失了。

通过做

this.testLogging 
    this.showStandardStreams = true
 

您只需将测试输出重定向到控制台。

相反,请查看TestLoggingContainer documentation 并考虑记录测试通过和失败,例如:

testLogging 
    events "passed", "failed"

【讨论】:

感谢您尝试回答我。我猜你没听懂我的意思。在 IntelliJ 中运行时,我确实看到了日志。问题是当我从命令行运行时,我看不到结果,我猜我的测试甚至没有被触发。我的问题只是关于从命令行运行时运行并查看结果。 我想我完全理解你的要求。在 IDE 中,您会看到一个结果窗口。在 CLI 上,Gradle 默认不打印任何测试输出。这来自于用户在一切顺利的情况下想要有限的输出。你试过我的建议了吗?用我建议的替换你的更改。 道歉。你是完全正确的:如果我同时添加“this.showStandardStreams = true”和“事件(“通过”,“失败”)”它只适用于 IntelliJ。当我拿出 showStandardStreams 时,我终于可以在命令行控制台中看到了。 确实,因为使用this.showStandardStreams = true,您的控制台日志会被 Spring 日志淹没。

以上是关于从命令行运行 gradle 时如何执行和显示友好的测试输出的主要内容,如果未能解决你的问题,请参考以下文章

如何从命令行运行单个 gradle 任务

如何通过命令行运行Maven / Gradle Web项目?

从命令行运行可执行文件时如何启用系统错误消息

运行从基于 gradle 的项目构建的可执行 jar 文件

如何在针对特定 Gradle 构建风格的同时从命令行运行单个单元测试方法

如何将参数从 gradle exec 任务传递到命令行