Spring Boot Spock测试中看不到痕迹

cgvd09ve  于 2023-01-20  发布在  Spring
关注(0)|答案(1)|浏览(119)

我试着在Spock测试中添加跟踪,看看测试容器是如何创建PostgreSQL容器的。但是无论是使用log4j,还是使用标准输出上的打印,或者使用例程扩展Spec,我都无法做到这一点。测试代码如下:

package com.makobrothers.mako.rrhh.persona.infrastructure.controller

import com.makobrothers.mako.IntegrationTest
import com.makobrothers.mako.MakoApplication
import org.junit.experimental.categories.Category
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.context.DynamicPropertyRegistry
import org.springframework.test.context.DynamicPropertySource
import org.springframework.test.context.TestPropertySource
import org.testcontainers.containers.PostgreSQLContainer
import org.testcontainers.spock.Testcontainers
import spock.lang.Shared;
import spock.lang.Specification

import java.text.DateFormat
import java.text.SimpleDateFormat
import static org.hamcrest.Matchers.*
import org.json.simple.JSONObject

@ActiveProfiles("test")
@Testcontainers
@SpringBootTest(
    webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,
    classes = MakoApplication.class
)
@TestPropertySource(locations = "classpath:application-test.yml")
@Category(IntegrationTest.class)
//@Sql(scripts = ["classpath:/createTablePersona.sql", "classpath:/insertTablePersona.sql"])
class PersonaRestAssuredSpec extends Specification {
    final static Logger log = LoggerFactory.getLogger(PersonaRestAssuredSpec.class)
    final static POSTGRES_TEST_IMAGE = "postgres:15.1"
    final static Random RANDOM = new Random();
    public static PostgreSQLContainer staticPostgreSQL = new PostgreSQLContainer(POSTGRES_TEST_IMAGE)
            .withDatabaseName("makoTest")
            .withUsername("mako")
            .withPassword("mako")
            .withExposedPorts(5432)
            .withCreateContainerCmdModifier({ cmd -> cmd.withName('postgreSQL-' + ( RANDOM.nextInt() & Integer.MAX_VALUE )) })

    @Shared
    public PostgreSQLContainer postgreSQLContainer = staticPostgreSQL
      
    @Value('\${server.http.port}')
    private int port

    def setup() throws Exception {
        RestAssured.port = port
        log.info("Url: " + postgreSQLContainer.getJdbcUrl())
        log.warn("Url: " + postgreSQLContainer.getJdbcUrl())
        log.error("Url: " + postgreSQLContainer.getJdbcUrl())
        showTrace "Url: " + postgreSQLContainer.getJdbcUrl()
        showTrace "DatabaseName: " + postgreSQLContainer.getDatabaseName()
        showTrace "Username: " + postgreSQLContainer.getUsername()
        showTrace "Password: " + postgreSQLContainer.getPassword()
        showTrace "Port: " + postgreSQLContainer.getBoundPortNumbers()
    }
    
    def "showConfigTest"() {
        given: "A client request to test findById"
            log.info("Url: " + postgreSQLContainer.getJdbcUrl())
            log.warn("Url: " + postgreSQLContainer.getJdbcUrl())
            log.error("Url: " + postgreSQLContainer.getJdbcUrl())
            showTrace "Url: " + postgreSQLContainer.getJdbcUrl()
            int left = 2
            int right = 2
        when: "Nothing"
            int result = left + right
        then: "Nothing"
            assert result == 4
    }
    
}

我用一个方法来扩展Spec以打印(SpockConfig.groovy),正如我在另一个查询中看到的示例:

import spock.lang.Specification

class LabelPrinter {
    def showTrace(def message) {
        println message
        true
    }
}

Specification.mixin LabelPrinter

gradle部分声明为:

test {
    useJUnitPlatform()

    testLogging {
        events "PASSED", "SKIPPED", "FAILED", "STANDARD_OUT", "STANDARD_ERROR"
    }
    
    testClassesDirs = sourceSets.test.output
    classpath = sourceSets.test.runtimeClasspath

    reports {
        html.enabled = true
    }
}

输出始终相同:

$ gradle clean test

> Task :test

  com.makobrothers.mako.rrhh.persona.infrastructure.controller.PersonaRestAssuredSpec

    ✔ showConfigTest (5.5s)
  1 passing (1m 15s)

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.6/userguide/command_line_interface.html#sec:command_line_warnings

BUILD SUCCESSFUL in 1m 27s
6 actionable tasks: 6 executed
lhcgjxsq

lhcgjxsq1#

将此功能添加到gradle,现在它可以正常工作了:

testlogger {
    // pick a theme - mocha, standard, plain, mocha-parallel, standard-parallel or plain-parallel
    theme 'mocha'
    // set to false to disable detailed failure logs
    showExceptions true
    // set threshold in milliseconds to highlight slow tests
    slowThreshold 2000
    // displays a breakdown of passes, failures and skips along with total duration
    showSummary true
    // set to false to hide passed tests
    showPassed true
    // set to false to hide skipped tests
    showSkipped true
    // set to false to hide failed tests
    showFailed true
    // enable to see standard out and error streams inline with the test results
    showStandardStreams true
    // set to false to hide passed standard out and error streams
    showPassedStandardStreams true
    // set to false to hide skipped standard out and error streams
    showSkippedStandardStreams true
    // set to false to hide failed standard out and error streams
    showFailedStandardStreams true
}

test {
    useJUnitPlatform()

    testLogging {
        outputs.upToDateWhen {false}
        showStandardStreams = true
        events "PASSED", "SKIPPED", "FAILED", "STANDARD_OUT", "STANDARD_ERROR"
    }
    
    testClassesDirs = sourceSets.test.output
    classpath = sourceSets.test.runtimeClasspath

    reports {
        html.enabled = true
    }
}

我认为是showStandardStreams属性允许查看日志。

相关问题