Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[INIT] RestDocs&Swagger 환경 세팅 #10

Merged
merged 3 commits into from
Jan 8, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions build.gradle
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오 제가 했던 스웨거랑 달라서 신기신기하네요

Original file line number Diff line number Diff line change
@@ -1,7 +1,33 @@
import org.hidetake.gradle.swagger.generator.GenerateSwaggerUI

buildscript {
ext {
restdocsApiSpecVersion = "0.18.2"
}
}

plugins {
id 'java'
id 'org.springframework.boot' version '3.2.1'
id 'io.spring.dependency-management' version '1.1.4'

// restdocs-swagger
id 'com.epages.restdocs-api-spec' version "${restdocsApiSpecVersion}"
id 'org.hidetake.swagger.generator' version '2.18.2'
}

swaggerSources {
sample {
setInputFile(file("${project.buildDir}/api-spec/openapi3.yaml"))
}
}

openapi3 {
server('http://localhost:8080')
title = 'API Documentation'
description = 'Spring REST Docs with SwaggerUI.'
version = '0.0.1'
format = 'yaml'
}

group = 'com.soptie'
Expand Down Expand Up @@ -33,8 +59,35 @@ dependencies {

// https://mvnrepository.com/artifact/org.postgresql/postgresql
implementation 'org.postgresql:postgresql:42.7.1'

// restdocs-swagger
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2'
testImplementation "com.epages:restdocs-api-spec-mockmvc:${restdocsApiSpecVersion}"
testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc'
}

tasks.named('test') {
useJUnitPlatform()
}

tasks.withType(GenerateSwaggerUI).configureEach {
dependsOn 'openapi3'
copy {
from "build/resources/main/static/docs"
into "src/main/resources/static/docs/"
}
}

bootJar {
dependsOn(':openapi3')
}

openapi3 {
server = "http://localhost:8080"
title = "소프티 API"
description = "소프티 API 명세서"
version = "0.0.1"
outputFileNamePrefix = 'open-api-3.0.1'
format = 'json'
outputDirectory = 'build/resources/main/static/docs'
}
16 changes: 16 additions & 0 deletions src/main/java/com/soptie/server/test/TestController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.soptie.server.test;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1/test")
public class TestController {

@GetMapping
public ResponseEntity<String> test() {
return ResponseEntity.ok("Success to server connect.");
}
}
1 change: 0 additions & 1 deletion src/main/resources/application.properties

This file was deleted.

6 changes: 6 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
springdoc:
default-consumes-media-type: application/json;charset=UTF-8
default-produces-media-type: application/json;charset=UTF-8
swagger-ui:
url: /docs/open-api-3.0.1.json
path: /swagger
46 changes: 46 additions & 0 deletions src/main/resources/static/docs/open-api-3.0.1.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
{
"openapi" : "3.0.1",
"info" : {
"title" : "smeme api documentation",
"description" : "Spring REST Docs with SwaggerUI.",
"version" : "0.0.1"
},
"servers" : [ {
"url" : "http://localhost:8080"
} ],
"tags" : [ ],
"paths" : {
"/api/v1/test" : {
"get" : {
"tags" : [ "TEST" ],
"summary" : "서버 연결 테스트",
"description" : "서버 연결 테스트",
"operationId" : "test-docs",
"responses" : {
"200" : {
"description" : "200",
"content" : {
"application/json;charset=UTF-8" : {
"schema" : {
"$ref" : "#/components/schemas/api-v1-test486549215"
},
"examples" : {
"test-docs" : {
"value" : "Success to server connect."
}
}
}
}
}
}
}
}
},
"components" : {
"schemas" : {
"api-v1-test486549215" : {
"type" : "object"
}
}
}
}
41 changes: 41 additions & 0 deletions src/test/java/com/soptie/server/base/BaseControllerTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package com.soptie.server.base;

import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.restdocs.RestDocumentationContextProvider;
import org.springframework.restdocs.RestDocumentationExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;

import com.fasterxml.jackson.databind.ObjectMapper;

@AutoConfigureMockMvc
@AutoConfigureRestDocs
@ExtendWith({RestDocumentationExtension.class})
public abstract class BaseControllerTest {

@Autowired
protected WebApplicationContext context;
@Autowired
protected ObjectMapper objectMapper;

protected MockMvc mockMvc;

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

나중에 띄어쓰기 없애주시면 감사하겠습니다!ㅋㅋㅋ


@BeforeEach
void setUp(final RestDocumentationContextProvider restDocumentation) {
mockMvc = MockMvcBuilders.webAppContextSetup(context)
.apply(documentationConfiguration(restDocumentation))
.addFilters(new CharacterEncodingFilter("UTF-8", true))
.alwaysDo(print())
.build();
}
}
58 changes: 58 additions & 0 deletions src/test/java/com/soptie/server/test/TestControllerTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package com.soptie.server.test;

import static com.epages.restdocs.apispec.ResourceDocumentation.resource;
import static org.mockito.Mockito.*;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.*;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation;
import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import com.epages.restdocs.apispec.ResourceSnippetParameters;
import com.soptie.server.base.BaseControllerTest;

@WebMvcTest(TestController.class)
public class TestControllerTest extends BaseControllerTest {

@MockBean
TestController testController;

private final String DEFAULT_URL = "/api/v1/test";
private final String TAG = "TEST";
Comment on lines +23 to +27
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

테스트 코드까지 작성하는 모습 너무 멋있습니다

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

인정인정

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@csb9427 @Chan531 감사합니다~! 앞으로 개발한 API는 이렇게 테스트 코드를 작성해야 스웨거에 포함되니 참고해주세요 :)


@Test
@DisplayName("서버 연결 테스트")
void success_test() throws Exception {
// given
ResponseEntity<String> response = ResponseEntity.ok("Success to server connect.");

//when
when(testController.test()).thenReturn(response);

//then
mockMvc
.perform(
RestDocumentationRequestBuilders.get(DEFAULT_URL)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andDo(
MockMvcRestDocumentation.document(
"test-docs",
preprocessRequest(prettyPrint()),
preprocessResponse(prettyPrint()),
resource(
ResourceSnippetParameters.builder()
.tag(TAG)
.description("서버 연결 테스트")
.requestFields()
.responseFields()
.build())))
.andExpect(MockMvcResultMatchers.status().isOk());
}
}