0
0

More than 1 year has passed since last update.

SpringBootTestでテスト時のみ使用するRestControllerを作成

Posted at

@SpringBootTestの際にmockなどではなくテスト時のみ有効になる@RestConrollerを使いたい場合のやり方について。@TestConfiguration@RestConrollerを定義する。

ソースコードなど

build.gradle
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";
    }
  }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0