|
| 1 | +# Kotlin + Spring demo |
| 2 | + |
| 3 | +## 실행 |
| 4 | + |
| 5 | +Run tests: |
| 6 | + |
| 7 | +```bash |
| 8 | +./gradlew test |
| 9 | +``` |
| 10 | + |
| 11 | +Build JAR: |
| 12 | + |
| 13 | +```bash |
| 14 | +./gradlew bootJar |
| 15 | +``` |
| 16 | + |
| 17 | +Run web server: |
| 18 | + |
| 19 | +```bash |
| 20 | +./gradlew bootRun |
| 21 | +``` |
| 22 | + |
| 23 | +<http://localhost:8080/> |
| 24 | + |
| 25 | +## 기본 코드 생성 |
| 26 | + |
| 27 | +Spring Initializr 사용: |
| 28 | +<https://start.spring.io/> |
| 29 | + |
| 30 | +## `WelcomeController` 테스트 및 구현 작성 |
| 31 | + |
| 32 | +참고: |
| 33 | + |
| 34 | +- [Kotlin + Spring Boot 맛보기](https://github.com/ahastudio/til/blob/main/spring/2019-12-04-kotlin-spring.md) |
| 35 | +- [Building web applications with Spring Boot and Kotlin](https://spring.io/guides/tutorials/spring-boot-kotlin/) |
| 36 | + |
| 37 | +`WelcomeControllerTest.kt` 파일 작성: |
| 38 | + |
| 39 | +```kotlin |
| 40 | +package com.example.demo.controllers |
| 41 | + |
| 42 | +import org.hamcrest.CoreMatchers.containsString |
| 43 | +import org.junit.jupiter.api.Test |
| 44 | +import org.springframework.beans.factory.annotation.Autowired |
| 45 | +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest |
| 46 | +import org.springframework.test.web.servlet.MockMvc |
| 47 | +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get |
| 48 | +import org.springframework.test.web.servlet.result.MockMvcResultMatchers.content |
| 49 | +import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status |
| 50 | + |
| 51 | +@WebMvcTest(WelcomeController::class) |
| 52 | +internal class WelcomeControllerTest(@Autowired val mockMvc: MockMvc) { |
| 53 | + |
| 54 | + @Test |
| 55 | + fun `GET ∕`() { |
| 56 | + mockMvc.perform(get("/")) |
| 57 | + .andExpect(status().isOk()) |
| 58 | + .andExpect(content().string(containsString("Hello"))) |
| 59 | + } |
| 60 | + |
| 61 | +} |
| 62 | +``` |
| 63 | + |
| 64 | +메서드 이름에 평범한 slash(`/`) 문자을 넣을 수 없어서 |
| 65 | +[유니코드 slash(`∕`) 문자](https://www.compart.com/en/unicode/U+2215)를 |
| 66 | +사용함. |
| 67 | + |
| 68 | +`WelcomeController.kt` 파일 작성: |
| 69 | + |
| 70 | +```kotlin |
| 71 | +package com.example.demo.controllers |
| 72 | + |
| 73 | +import org.springframework.web.bind.annotation.GetMapping |
| 74 | +import org.springframework.web.bind.annotation.RestController |
| 75 | + |
| 76 | +@RestController |
| 77 | +class WelcomeController { |
| 78 | + |
| 79 | + @GetMapping |
| 80 | + fun home(): String { |
| 81 | + return "Hello, world!" |
| 82 | + } |
| 83 | + |
| 84 | +} |
| 85 | +``` |
0 commit comments