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

问题描述 投票:0回答:1

我可以很容易地从IntelliJ IDEA中运行我的项目测试,但我很难从命令行中运行它们并看到结果。

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

tasks.test {
    useJUnitPlatform()
}

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

从下图可以看出,所有的测试都在运行,我可以在IntelliJ中看到结果。

INtelliJ

然而,当我在同一项目中从Windows命令行尝试时,我得到的是

C:/WSs/KotlinGradleIntelliJ/jokenpo>gradlew test

> 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配置来shw结果,甚至最糟糕的是,我的测试根本没有被执行,我失去了一些基本的概念,因为IntelliJ自动添加了这个,并 "隐藏 "在我的眼睛。

spring-boot kotlin gradle intellij-idea junit
1个回答
1
投票

当使用Gradle rich console时,测试执行情况会在Gradle输出的动态部分报告。这意味着,一旦测试完成,该输出就会消失。

通过做

this.testLogging {
    this.showStandardStreams = true
} 

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

相反,请看一下 TestLoggingContainer 文件 并考虑用类似这样的方式记录测试通过和失败。

testLogging {
    events "passed", "failed"
}
© www.soinside.com 2019 - 2024. All rights reserved.