【问题标题】:Spring feature OutputCapture does not work in valid spring boot versionSpring 功能 OutputCapture 在有效的 Spring Boot 版本中不起作用
【发布时间】:2018-03-06 13:25:46
【问题描述】:

我无法在JUnit testing 内使用带有OutputCapture 的功能。我想使用此功能查看一些日志消息。 如果我尝试在 IDEA 中包含类包 org.springframework.book.test.rule.OutputCapture,它会显示警告消息“无建议”。这样我就无法访问 outputCapture 类(甚至测试包不可见)。

正如我在website 上发现的那样,自 1.3 版起支持此类。 但是我使用的是正确的 Spring Boot 1.5 版。

import org.junit.Rule;
import org.junit.Test;
import org.springframework.boot.test.rule.OutputCapture; THIS IS NOT RECOGNIZED

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

public class MyTest {

    @Rule
    public OutputCapture capture = new OutputCapture();

    @Test
    public void testName() throws Exception {
        System.out.println("Hello World!");
        assertThat(capture.toString(), containsString("World"));
    }

}

怎么了?

【问题讨论】:

  • 可以添加junit代码吗?
  • “这无法识别”是什么意思?
  • 这意味着如果我尝试在 IDEA 中选择 org.springframework.book.test,它会显示警告消息“没有建议”。这样我就无法访问 outputCapture 类。我将编辑我的问题。
  • 您是否在配置(maven?)中添加了对 Spring Boot 测试的依赖?请出示您的pom.xml

标签: java spring junit


【解决方案1】:

只是一个广泛的猜测,因为我不知道您的依赖关系:如果您使用的是 maven,请尝试添加以下依赖项:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <version>2.1.6.RELEASE</version> <!-- or another version -->
    <scope>test</scope>
</dependency>

原因是OutputCapture来自spring-boot-test项目。

Github:OutputCapture

【讨论】:

    【解决方案2】:

    OutputCapture 类在 Spring Boot 测试中的版本 2.2.0 中为 deprecated,支持 OutputCaptureRule 类。

    查看answer 了解如何使用OutputCaptureRule 类。

    【讨论】:

      猜你喜欢
      • 2020-03-23
      • 2018-08-27
      • 2019-02-05
      • 2021-04-04
      • 2020-04-10
      • 2018-01-18
      • 2018-12-14
      • 1970-01-01
      • 2017-09-26
      相关资源
      最近更新 更多