创建一个仅在测试时使用的 SpringBootTest RestController

关于如何在@TestConfiguration中定义@RestConroller,以便在@SpringBootTest期间仅在测试时生效,而不使用mock等。

源代码等

plugins {
  id 'java'
  id 'org.springframework.boot' version '3.1.2'
  id 'io.spring.dependency-management' version '1.1.2'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'

java {
  sourceCompatibility = '17'
}

configurations {
  compileOnly {
    extendsFrom annotationProcessor
  }
}

repositories {
  mavenCentral()
}

dependencies {
  implementation 'org.springframework.boot:spring-boot-starter-web'
  compileOnly 'org.projectlombok:lombok'
  developmentOnly 'org.springframework.boot:spring-boot-devtools'
  annotationProcessor 'org.projectlombok:lombok'
  testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

tasks.named('test') {
  useJUnitPlatform()
}
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class IntegrationTest {

  @LocalServerPort
  int port;

  @Test
  void test() {
    RestTemplate client = new RestTemplate();
    String result = client.getForObject("http://localhost:" + port + "/sample", String.class);

    System.out.println(result);
  }

  @TestConfiguration
  @RestController
  static class Hoge {

    @GetMapping("/sample")
    String sample() {
      return "sample";
    }
  }
}

广告
将在 10 秒后关闭
bannerAds