标签: spring-boot-test

SpringRunner 与 SpringBootTest

在单元测试中,@Runwith(SpringRunner.class)&之间有什么区别@SpringBootTest

你能向我解释一下每一种的用例吗?

java junit spring-boot spring-boot-test

45
推荐指数
3
解决办法
3万
查看次数

找不到SpringApplicationConfiguration:错误的spring-boot-starter-test内容?

在Maven中获取编译错误:

[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR : 
[INFO] -------------------------------------------------------------
[ERROR] /C:/prototypes/demo-sse-spring-boot-master/src/test/java/com/cedric/demo/sse/SseDemoApplicationTests.java:[6,37] package org.springframework.boot.test does not exist
[ERROR] /C:/TITAN/demo-sse-spring-boot-master/src/test/java/com/cedric/demo/sse/SseDemoApplicationTests.java:[10,2] cannot find symbol
  symbol: class SpringApplicationConfiguration
[INFO] 2 errors 
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)

Maven回购似乎有罐子存在:

在此输入图像描述

但是那个jar里面没有任何编译过的类.只有META-INF目录:

在此输入图像描述

这是设计的吗?我在哪里获得包含SpringApplicationConfiguration类的jar 以使Maven满意?

这是我的pom.xml的相关部分:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
        <relativePath/>
        <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

        <dependency>
            <groupId>org.webjars.bower</groupId>
            <artifactId>jquery</artifactId>
            <version>2.1.3</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId> …
Run Code Online (Sandbox Code Playgroud)

testing maven spring-boot spring-boot-test

21
推荐指数
3
解决办法
3万
查看次数

junit-vintage-engine 和junit-jupiter-engine 的区别?

这是一个双重问题。

  1. junit-vintage-engine和 和有junit-jupiter-engine什么区别?
  2. SpringBoot 入门项目排除了junit-vintage-engine. 是否强制使用junit-jupiter-engine?

下面是我从Spring Initializr生成的 SpringBoot 项目的依赖项:

        <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
Run Code Online (Sandbox Code Playgroud)

java junit spring-boot spring-boot-test

18
推荐指数
2
解决办法
2万
查看次数

@SpringbootTest 中缺少 /actuator/prometheus

我正在使用 springboot 2.4.0,并添加了以下依赖项以启用 prometheus 指标:

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
        <groupId>io.micrometer</groupId>
        <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)

然后在我的 application.properties 我有以下属性

management.endpoints.web.exposure.include=*
management.metrics.enable.all=true
Run Code Online (Sandbox Code Playgroud)

我正在尝试运行一个简单的集成测试,以查看我的自定义指标出现在 /actuator/prometheus 端点上。代码下方

package com.example.demo;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import static io.restassured.RestAssured.given;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class IntegrationTest {

  @LocalServerPort
  private int port;

  private String baseUrl;

  @BeforeEach
  public void setup() {
      baseUrl = "http://localhost:" + port;
  }

  @Test
  public void metricsEndpoint() throws Exception {

    given().when().get(baseUrl + "/demo/actuator/prometheus")
            .then()
            .statusCode(200);
    }
}
Run Code Online (Sandbox Code Playgroud)

我在这里得到的错误是

java.lang.AssertionError: 1 expectation failed.
Expected status …
Run Code Online (Sandbox Code Playgroud)

java metrics spring-boot-actuator spring-boot-test spring-micrometer

17
推荐指数
3
解决办法
1508
查看次数

由于缺少ReactiveWebServerFactory bean,无法启动ReactiveWebApplicationContext

我有一个新的springboot应用程序,我试图开始.

我收到的错误是

org.springframework.context.ApplicationContextException: Unable to start reactive web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ReactiveWebApplicationContext due to missing ReactiveWebServerFactory bean.
    at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.onRefresh(ReactiveWebServerApplicationContext.java:76) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
Run Code Online (Sandbox Code Playgroud)

的src /主/爪哇/ bubbleshadow/RootController.java

package bubbleshadow;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@RestController
public class RootController {
  public RootController() {

  }

  @GetMapping("/")
  public Mono<HttpStatus> returnOk() {
    return Mono.just(HttpStatus.OK);
  }
}
Run Code Online (Sandbox Code Playgroud)

的src /测试/ JAVA /测试/ bubbleshadow/RootControllerTest.java

package test.bubbleshadow;
import bubbleshadow.RootController;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
// import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.boot.test.context.SpringBootTest; …
Run Code Online (Sandbox Code Playgroud)

java spring-boot spring-boot-test

13
推荐指数
4
解决办法
5150
查看次数

如何在集成测试中一起使用这些@DataMongoTest 和@SpringBootTest

我正在尝试为我的其余应用程序之一编写集成测试用例,该应用程序在内部使用 mongodb 来持久化数据

@DataMongoTest 
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class MainControllerTest {
@LocalServerPort
    private int port = 8080;
/* some test cases*/ 
}
Run Code Online (Sandbox Code Playgroud)

但我得到以下错误

java.lang.IllegalStateException: Configuration error: found multiple declarations of @BootstrapWith for test class [com.sample.core.controller.MainControllerTest]: [@org.springframework.test.context.BootstrapWith(value=class org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTestContextBootstrapper), @org.springframework.test.context.BootstrapWith(value=class org.springframework.boot.test.context.SpringBootTestContextBootstrapper)]
Run Code Online (Sandbox Code Playgroud)

看起来这两者是相互排斥的,那么如何进行集成测试。

junit integration-testing spring-boot-test

13
推荐指数
1
解决办法
6409
查看次数

@webMvcTest 不排除并加载标记为 @Repository 的 bean

我有一个@RestController 在字段中只有一个依赖项@Autowire ,依赖项是@component,该组件类定义有一些自动装配的字段,它们是@service,这些服务有一些@repositories。

在整个流程中,我使用了 kafka、Quartz、Cassandra 和 DB2,因此当我为控制器创建单元测试用例时,我不想设置整个应用程序。所以我决定使用 @webMvcTest 并在我唯一的一个控制器类依赖项上使用 @MockBean。

但我的测试抛出异常,因为它试图创建一个 Dao bean,它被标记为 @repository。

@ActiveProfiles("test")
@WebMvcTest(controllers = MyControllerTest .class)
class MyControllerTest {

    @MockBean
    MyControllerDependency dependency;

    @Autowired
    MockMvc mockMvc;

    @Test
    void test_something() throws Exception {
       assert(true);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是代码的过于简化的版本

@Component
class MyControllerDependency { 
    @AutoiWired
    MyCustomService service;
}

@Service
class MyCustomService{

   @Autowired
   MyCustomDao dao;
}

@Repository
class MyCustomDao{
    @Autowired
    private JdbcTemplate template;
}
Run Code Online (Sandbox Code Playgroud)

我在测试中遇到以下异常。

Exception

***************************
APPLICATION FAILED TO START
***************************

Description:

Field template in com.....MyCustomDao`  required a bean of …
Run Code Online (Sandbox Code Playgroud)

spring spring-test spring-boot-test

13
推荐指数
2
解决办法
1万
查看次数

使用Spring Embedded Kafka测试@KafkaListener

我正在尝试为使用Spring Boot 2.x开发的Kafka监听器编写单元测试.作为一个单元测试,我不想启动一个完整的Kafka服务器作为Zookeeper的一个实例.所以,我决定使用Spring Embedded Kafka.

我的听众的定义非常基本.

@Component
public class Listener {
    private final CountDownLatch latch;

    @Autowired
    public Listener(CountDownLatch latch) {
        this.latch = latch;
    }

    @KafkaListener(topics = "sample-topic")
    public void listen(String message) {
        latch.countDown();
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,latch在接收消息后验证计数器等于零的测试非常容易.

@RunWith(SpringRunner.class)
@SpringBootTest
@DirtiesContext
@EmbeddedKafka(topics = { "sample-topic" })
@TestPropertySource(properties = { "spring.kafka.bootstrap-servers=${spring.embedded.kafka.brokers}" })
public class ListenerTest {

    @Autowired
    private KafkaEmbedded embeddedKafka;

    @Autowired
    private CountDownLatch latch;

    private KafkaTemplate<Integer, String> producer;

    @Before
    public void setUp() {
        this.producer = buildKafkaTemplate();
        this.producer.setDefaultTopic("sample-topic");
    }

    private KafkaTemplate<Integer, String> …
Run Code Online (Sandbox Code Playgroud)

java apache-kafka spring-boot spring-kafka spring-boot-test

12
推荐指数
1
解决办法
7941
查看次数

如何防止在@SpringBootTest 启动期间记录噪音?

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
                    properties = "logging.level.root=OFF")
public class MyTest {
         @Test
         public void test() {}
}
Run Code Online (Sandbox Code Playgroud)

作为上述简单测试的结果,我记录了很多启动噪音。在升级到 spring-boot-2.x 之前,情况并非如此。我怎样才能防止这种噪音?

特别是,我的 Intellij IDE 将这些语句记录为red,这在测试本身通过时更加令人困惑......

Jul 31, 2018 1:55:57 PM org.springframework.boot.test.context.SpringBootTestContextBootstrapper buildDefaultMergedContextConfiguration
INFO: Neither @ContextConfiguration nor @ContextHierarchy found for test class [MyTest], using SpringBootContextLoader
Jul 31, 2018 1:55:57 PM org.springframework.test.context.support.AbstractContextLoader generateDefaultLocations
INFO: Could not detect default resource locations for test class [MyTest]: no resource found for suffixes {-context.xml, Context.groovy}.
Jul 31, 2018 1:55:57 PM org.springframework.test.context.support.AnnotationConfigContextLoaderUtils detectDefaultConfigurationClasses
INFO: Could not …
Run Code Online (Sandbox Code Playgroud)

java spring spring-boot spring-boot-test

12
推荐指数
1
解决办法
1511
查看次数

在 SpringBootTest 中禁用使用 spring.config.import 激活的配置服务客户端

我有一个裸露的 Spring Boot 应用程序

@SpringBootApplication
public class ClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(ClientApplication.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

它通过以下内容连接到 Spring Cloud Config Serverapplication.yml

spring:
  application:
    name: client

  config:
    import: configserver:http://localhost:8888
Run Code Online (Sandbox Code Playgroud)

当配置服务器正在运行时,应用程序工作正常,而当服务器未运行时,应用程序会按预期失败。

我现在想@SpringBootTest为不依赖于正在运行的配置服务器的应用程序编写一个集成测试,甚至不尝试连接到它。

配置服务器关闭后,进行裸测试

@SpringBootTest
class ClientApplicationTests {
    @Test
    void contextLoads() {
    }
}
Run Code Online (Sandbox Code Playgroud)

失败并显示java.net.ConnectException: Connection refused,这是预期的。

当我尝试禁用配置客户端时

@SpringBootTest(properties = "spring.cloud.config.enabled=false")
Run Code Online (Sandbox Code Playgroud)

测试不会尝试连接到服务器,但失败并显示

Failed to load ApplicationContext
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
    ...
Caused by: java.lang.IllegalStateException: Unable to load config data from 'configserver:http://localhost:8888'
    at …
Run Code Online (Sandbox Code Playgroud)

spring-boot spring-cloud-config spring-boot-test

12
推荐指数
2
解决办法
9033
查看次数