├── .github └── workflows │ └── sonarcloud-analyze.yml ├── .gitignore ├── Jenkinsfile ├── README.md ├── build.gradle.kts ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src ├── main ├── java │ └── com │ │ └── flab │ │ └── modu │ │ ├── ModuUiMarketApplication.java │ │ ├── admin │ │ ├── controller │ │ │ └── AdminController.java │ │ └── service │ │ │ └── AdminService.java │ │ ├── global │ │ ├── annotation │ │ │ ├── CurrentUser.java │ │ │ └── LoginCheck.java │ │ ├── config │ │ │ ├── JpaConfig.java │ │ │ ├── LoginUserArgumentResolver.java │ │ │ └── WebConfig.java │ │ ├── domain │ │ │ └── BaseTimeEntity.java │ │ ├── exception │ │ │ └── GlobalExceptionHandler.java │ │ ├── interceptor │ │ │ └── LoginCheckInterceptor.java │ │ └── response │ │ │ └── ErrorResponseDto.java │ │ ├── market │ │ ├── controller │ │ │ ├── MarketController.java │ │ │ └── MarketDto.java │ │ ├── domain │ │ │ ├── Market.java │ │ │ └── MarketStatus.java │ │ ├── exception │ │ │ ├── DuplicatedUrlException.java │ │ │ ├── MarketNoPermissionException.java │ │ │ └── MarketNotFoundException.java │ │ ├── repository │ │ │ └── MarketRepository.java │ │ └── service │ │ │ └── MarketService.java │ │ ├── order │ │ ├── controller │ │ │ ├── OrderController.java │ │ │ └── OrderDto.java │ │ ├── domain │ │ │ ├── common │ │ │ │ └── OrderStatus.java │ │ │ └── entity │ │ │ │ ├── Order.java │ │ │ │ └── OrderProduct.java │ │ ├── exception │ │ │ └── OrderFailureException.java │ │ ├── repository │ │ │ └── OrderRepository.java │ │ └── service │ │ │ ├── OrderCallService.java │ │ │ └── OrderService.java │ │ ├── product │ │ ├── controller │ │ │ ├── ProductController.java │ │ │ └── ProductDto.java │ │ ├── converter │ │ │ └── ProductStatusCodeRequestConverter.java │ │ ├── domain │ │ │ ├── common │ │ │ │ └── ProductStatus.java │ │ │ └── entity │ │ │ │ └── Product.java │ │ ├── exception │ │ │ ├── InsufficientStockException.java │ │ │ ├── NotExistProductException.java │ │ │ └── WrongImageDataException.java │ │ ├── repository │ │ │ └── ProductRepository.java │ │ └── service │ │ │ └── ProductService.java │ │ └── users │ │ ├── controller │ │ ├── UserController.java │ │ └── UserDto.java │ │ ├── domain │ │ ├── common │ │ │ ├── UserConstant.java │ │ │ └── UserRole.java │ │ └── entity │ │ │ └── User.java │ │ ├── encoder │ │ └── PasswordEncoder.java │ │ ├── exception │ │ ├── DuplicatedEmailException.java │ │ ├── NotExistedUserException.java │ │ ├── UnauthenticatedUserException.java │ │ └── WrongPasswordException.java │ │ ├── repository │ │ ├── UserRepository.java │ │ ├── UserRepositoryCustom.java │ │ └── UserRepositoryImpl.java │ │ └── service │ │ ├── LoginService.java │ │ └── UserService.java └── resources │ ├── application-product.yml │ └── application.yml └── test ├── java └── com │ └── flab │ └── modu │ ├── ModuUiMarketApplicationTests.java │ ├── admin │ ├── controller │ │ └── AdminControllerTest.java │ └── service │ │ └── AdminServiceTest.java │ ├── market │ ├── controller │ │ └── MarketControllerTest.java │ ├── repository │ │ └── MarketRepositoryTest.java │ └── service │ │ └── MarketServiceTest.java │ ├── order │ ├── controller │ │ └── OrderControllerTest.java │ └── service │ │ ├── OrderServiceConcurrencyTest.java │ │ └── OrderServiceTest.java │ ├── product │ ├── controller │ │ └── ProductControllerTest.java │ ├── repository │ │ └── ProductRepositoryTest.java │ └── service │ │ └── ProductServiceTest.java │ └── users │ ├── controller │ └── UserControllerTest.java │ ├── repository │ └── UserRepositoryTest.java │ └── service │ ├── LoginServiceTest.java │ └── UserServiceTest.java └── resources └── application.yml /.github/workflows/sonarcloud-analyze.yml: -------------------------------------------------------------------------------- 1 | name: F-Lab SonarCloud Code Analyze 2 | 3 | on: 4 | pull_request: 5 | types: [opened, synchronize, reopened] 6 | workflow_dispatch: 7 | 8 | env: 9 | CACHED_DEPENDENCIES_PATHS: '**/node_modules' 10 | 11 | jobs: 12 | CodeAnalyze: 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v3 17 | with: 18 | fetch-depth: 0 19 | 20 | - name: Set SonarCloud Project Key 21 | run: | 22 | REPO_NAME=$(echo $GITHUB_REPOSITORY | cut -d '/' -f 2) 23 | ORG_NAME=$(echo $GITHUB_REPOSITORY | cut -d '/' -f 1) 24 | SONAR_PROJECT_KEY="${ORG_NAME}_${REPO_NAME}" 25 | echo "SONAR_PROJECT_KEY=$SONAR_PROJECT_KEY" >> $GITHUB_ENV 26 | 27 | - name: Set up JDK 28 | uses: actions/setup-java@v2 29 | with: 30 | java-version: '19' 31 | distribution: 'adopt' 32 | 33 | - name: Create Sonar Gradle File 34 | run: | 35 | insert_string="plugins { id 'org.sonarqube' version '4.4.1.3373' }" 36 | if [ -f "build.gradle" ]; then 37 | echo "$insert_string" > temp.gradle 38 | cat build.gradle >> temp.gradle 39 | echo "" >> temp.gradle 40 | echo "sonarqube {" >> temp.gradle 41 | echo " properties {" >> temp.gradle 42 | echo " property 'sonar.java.binaries', '**'" >> temp.gradle 43 | echo " }" >> temp.gradle 44 | echo "}" >> temp.gradle 45 | mv temp.gradle build.gradle 46 | else 47 | echo "$insert_string" > build.gradle 48 | echo "" >> build.gradle 49 | echo "sonarqube {" >> build.gradle 50 | echo " properties {" >> build.gradle 51 | echo " property 'sonar.java.binaries', '**'" >> build.gradle 52 | echo " }" >> build.gradle 53 | echo "}" >> build.gradle 54 | fi 55 | 56 | 57 | - name: Analyze 58 | run: ./gradlew sonar -Dsonar.projectKey=${{ env.SONAR_PROJECT_KEY }} -Dsonar.organization=f-lab-edu-1 -Dsonar.host.url=https://sonarcloud.io -Dsonar.token=${{ secrets.SECRET_SONARQUBE }} -Dsonar.gradle.skipCompile=true 59 | env: 60 | SONAR_TOKEN: ${{ secrets.SECRET_SONARQUBE }} 61 | 62 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /Jenkinsfile: -------------------------------------------------------------------------------- 1 | echo "---build start---" 2 | 3 | pipeline { 4 | agent any 5 | environment { 6 | FROM_EMAIL = 'modu-ui-market jenkins '; 7 | } 8 | stages{ 9 | stage('Git Checkout') { 10 | steps { 11 | checkout scm 12 | echo 'Git Checkout Success!' 13 | } 14 | post { 15 | failure { 16 | doFailPost(); 17 | } 18 | } 19 | } 20 | 21 | stage('Test') { 22 | steps { 23 | sh 'chmod +x gradlew' 24 | sh './gradlew test' 25 | echo 'test success' 26 | } 27 | post { 28 | failure { 29 | doFailPost(); 30 | } 31 | } 32 | } 33 | 34 | stage('Build') { 35 | steps { 36 | sh './gradlew clean build -x test' 37 | echo 'build success' 38 | } 39 | post { 40 | failure { 41 | doFailPost(); 42 | } 43 | } 44 | } 45 | 46 | stage('Deploy') { 47 | when{ 48 | branch 'develop' 49 | } 50 | steps { 51 | sshagent(credentials: ['deploy_server_ssh_key']) { 52 | sh "ssh -o StrictHostKeyChecking=no moma@${env.DEPLOY_HOST} -p ${env.DEPLOY_PORT} uptime" 53 | sh "scp -P ${env.DEPLOY_PORT} ./build/libs/modu-0.0.1-SNAPSHOT.jar moma@${env.DEPLOY_HOST}:/home/moma/modu" 54 | sh "ssh -o StrictHostKeyChecking=no -t moma@${env.DEPLOY_HOST} -p ${env.DEPLOY_PORT} ./deploy.sh product ${env.DB_URL} ${env.DB_USERNAME} ${env.DB_PASSWORD}" 55 | } 56 | echo 'deploy success' 57 | } 58 | post { 59 | failure { 60 | doFailPost(); 61 | } 62 | } 63 | } 64 | } 65 | post { 66 | success { 67 | setBuildStatus("Build succeeded", "SUCCESS"); 68 | } 69 | } 70 | } 71 | 72 | void setBuildStatus(String message, String state){ 73 | step([ 74 | $class: "GitHubCommitStatusSetter", 75 | reposSource: [$class: "ManuallyEnteredRepositorySource", url: "https://github.com/f-lab-edu/modu-ui-market"], 76 | contextSource: [$class: "ManuallyEnteredCommitContextSource", context: "ci/jenkins/modu-ui-market/build-status"], 77 | errorHandlers: [[$class: "ChangingBuildStatusErrorHandler", result:"UNSTABLE"]], 78 | statusResultSource: [$class: "ConditionalStatusResultSource", results: [[$class: "AnyBuildResult", message: message, state: state]]] 79 | ]); 80 | } 81 | 82 | void doFailPost(){ 83 | echo "[${env.STAGE_NAME}] stage failed..." 84 | setBuildStatus("Build failed [stage:${env.STAGE_NAME}]", 'FAILURE'); 85 | 86 | def buildLogStr = currentBuild.rawBuild.getLog(100).join('\n') 87 | 88 | emailext subject: "${env.BRANCH_NAME} - Build#${currentBuild.number} - ${currentBuild.currentResult}!", 89 | body: """branch : ${env.BRANCH_NAME}
90 | url : ${env.JOB_URL}
91 | build number : Build#${currentBuild.number}
92 | stage : ${env.STAGE_NAME}
93 | result : ${currentBuild.currentResult}
94 | duration : ${currentBuild.duration/1000}s
95 |
96 | build log 97 |
98 |
"""+buildLogStr+"
", 99 | from: "${env.FROM_EMAIL}", 100 | to: "${env.FROM_EMAIL}", 101 | recipientProviders : [developers(),culprits(),buildUser()] 102 | } 103 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # modu-ui-market 2 | 3 | ## 1. 서비스 설명 4 | 자신만의 마켓을 만들어 물건을 판매할 수 있는 오픈마켓 서비스입니다. 5 | 6 | ## 2. ERD 7 | ![modu-ui-market (1)](https://user-images.githubusercontent.com/19955465/215963967-cfdbb041-b121-4211-8138-d20bd72adb8a.png) 8 | 9 | ## 3. CI/CD 구조 10 | ![CICD구성도](https://github.com/f-lab-edu/modu-ui-market/assets/19955465/6306f9de-3eb0-4226-8080-c720a4cad9bc) 11 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | java 3 | id("org.springframework.boot") version "2.7.7" 4 | id("io.spring.dependency-management") version "1.0.15.RELEASE" 5 | id("org.asciidoctor.jvm.convert") version "3.3.2" 6 | } 7 | 8 | group = "com.flab" 9 | version = "0.0.1-SNAPSHOT" 10 | java.sourceCompatibility = JavaVersion.VERSION_11 11 | 12 | configurations { 13 | compileOnly { 14 | extendsFrom(configurations.annotationProcessor.get()) 15 | } 16 | } 17 | 18 | repositories { 19 | mavenCentral() 20 | } 21 | 22 | extra["snippetsDir"] = file("build/generated-snippets") 23 | 24 | dependencies { 25 | implementation("org.springframework.boot:spring-boot-starter-data-jpa") 26 | implementation("org.springframework.boot:spring-boot-starter-validation") 27 | implementation("org.springframework.boot:spring-boot-starter-web") 28 | implementation("org.apache.commons:commons-lang3:3.12.0") 29 | compileOnly("org.projectlombok:lombok") 30 | developmentOnly("org.springframework.boot:spring-boot-devtools") 31 | runtimeOnly("mysql:mysql-connector-java") 32 | runtimeOnly("com.h2database:h2") 33 | annotationProcessor("org.projectlombok:lombok") 34 | testImplementation("org.springframework.boot:spring-boot-starter-test") 35 | testImplementation("org.springframework.restdocs:spring-restdocs-asciidoctor") 36 | testImplementation("org.springframework.restdocs:spring-restdocs-mockmvc") 37 | 38 | //Querydsl 추가 39 | implementation("com.querydsl:querydsl-jpa") 40 | annotationProcessor("com.querydsl:querydsl-apt:${dependencyManagement.importedProperties["querydsl.version"]}:jpa") 41 | annotationProcessor("jakarta.annotation:jakarta.annotation-api") 42 | annotationProcessor("jakarta.persistence:jakarta.persistence-api") 43 | } 44 | 45 | tasks.register("customClean") { 46 | doLast { 47 | delete("src/main/generated") 48 | } 49 | } 50 | 51 | tasks.named("clean").configure { 52 | dependsOn("customClean") 53 | } 54 | 55 | tasks { 56 | withType { 57 | useJUnitPlatform() 58 | } 59 | 60 | val snippetsDir = file("$buildDir/generated-snippets") 61 | 62 | clean { 63 | delete("src/main/resources/static/docs") 64 | } 65 | 66 | test { 67 | useJUnitPlatform() 68 | systemProperty("org.springframework.restdocs.outputDir", snippetsDir) 69 | outputs.dir(snippetsDir) 70 | } 71 | 72 | build { 73 | dependsOn("copyDocument") 74 | } 75 | 76 | asciidoctor { 77 | dependsOn(test) 78 | 79 | attributes( 80 | mapOf("snippets" to snippetsDir) 81 | ) 82 | inputs.dir(snippetsDir) 83 | 84 | doFirst { 85 | delete("src/main/resources/static/docs") 86 | } 87 | } 88 | 89 | register("copyDocument") { 90 | dependsOn(asciidoctor) 91 | 92 | destinationDir = file(".") 93 | from(asciidoctor.get().outputDir) { 94 | into("src/main/resources/static/docs") 95 | } 96 | } 97 | 98 | bootJar { 99 | dependsOn(asciidoctor) 100 | 101 | from(asciidoctor.get().outputDir) { 102 | into("BOOT-INF/classes/static/docs") 103 | } 104 | } 105 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/f-lab-edu/modu-ui-market/5ff136a198504bed03fb728276cc87062505a477/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Stop when "xargs" is not available. 209 | if ! command -v xargs >/dev/null 2>&1 210 | then 211 | die "xargs is not available" 212 | fi 213 | 214 | # Use "xargs" to parse quoted args. 215 | # 216 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 217 | # 218 | # In Bash we could simply go: 219 | # 220 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 221 | # set -- "${ARGS[@]}" "$@" 222 | # 223 | # but POSIX shell has neither arrays nor command substitution, so instead we 224 | # post-process each arg (as a line of input to sed) to backslash-escape any 225 | # character that might be a shell metacharacter, then use eval to reverse 226 | # that process (while maintaining the separation between arguments), and wrap 227 | # the whole thing up as a single "set" statement. 228 | # 229 | # This will of course break if any of these variables contains a newline or 230 | # an unmatched quote. 231 | # 232 | 233 | eval "set -- $( 234 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 235 | xargs -n1 | 236 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 237 | tr '\n' ' ' 238 | )" '"$@"' 239 | 240 | exec "$JAVACMD" "$@" 241 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if %ERRORLEVEL% equ 0 goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if %ERRORLEVEL% equ 0 goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | set EXIT_CODE=%ERRORLEVEL% 84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 86 | exit /b %EXIT_CODE% 87 | 88 | :mainEnd 89 | if "%OS%"=="Windows_NT" endlocal 90 | 91 | :omega 92 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "modu" 2 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/ModuUiMarketApplication.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class ModuUiMarketApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(ModuUiMarketApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/admin/controller/AdminController.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.admin.controller; 2 | 3 | import com.flab.modu.admin.service.AdminService; 4 | import com.flab.modu.users.controller.UserDto.UserResponse; 5 | import com.flab.modu.users.controller.UserDto.UserSearchCondition; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.data.domain.Page; 8 | import org.springframework.data.domain.Pageable; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.RestController; 12 | 13 | @RequiredArgsConstructor 14 | @RequestMapping("/admin") 15 | @RestController 16 | public class AdminController { 17 | 18 | private final AdminService adminService; 19 | 20 | @GetMapping("/users") 21 | public Page findByUsers(UserSearchCondition condition, Pageable pageable) { 22 | return adminService.findUsers(condition, pageable); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/admin/service/AdminService.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.admin.service; 2 | 3 | import com.flab.modu.users.controller.UserDto.UserResponse; 4 | import com.flab.modu.users.controller.UserDto.UserSearchCondition; 5 | import com.flab.modu.users.repository.UserRepository; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.data.domain.Page; 8 | import org.springframework.data.domain.Pageable; 9 | import org.springframework.stereotype.Service; 10 | import org.springframework.transaction.annotation.Transactional; 11 | 12 | @Service 13 | @RequiredArgsConstructor 14 | public class AdminService { 15 | 16 | private final UserRepository userRepository; 17 | 18 | @Transactional(readOnly = true) 19 | public Page findUsers(UserSearchCondition condition, Pageable pageable) { 20 | return userRepository.searchByUsers(condition, pageable); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/global/annotation/CurrentUser.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.global.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Target({ElementType.PARAMETER}) 9 | @Retention(RetentionPolicy.RUNTIME) 10 | public @interface CurrentUser { 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/global/annotation/LoginCheck.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.global.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Target({ElementType.METHOD}) 9 | @Retention(RetentionPolicy.RUNTIME) 10 | public @interface LoginCheck { 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/global/config/JpaConfig.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.global.config; 2 | 3 | import com.querydsl.jpa.impl.JPAQueryFactory; 4 | import javax.persistence.EntityManager; 5 | import javax.persistence.PersistenceContext; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.data.jpa.repository.config.EnableJpaAuditing; 9 | 10 | @EnableJpaAuditing 11 | @Configuration 12 | public class JpaConfig { 13 | 14 | @PersistenceContext 15 | private EntityManager entityManager; 16 | 17 | @Bean 18 | public JPAQueryFactory queryFactory() { 19 | return new JPAQueryFactory(entityManager); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/global/config/LoginUserArgumentResolver.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.global.config; 2 | 3 | import com.flab.modu.global.annotation.CurrentUser; 4 | import com.flab.modu.users.service.LoginService; 5 | import lombok.RequiredArgsConstructor; 6 | import org.springframework.core.MethodParameter; 7 | import org.springframework.stereotype.Component; 8 | import org.springframework.web.bind.support.WebDataBinderFactory; 9 | import org.springframework.web.context.request.NativeWebRequest; 10 | import org.springframework.web.method.support.HandlerMethodArgumentResolver; 11 | import org.springframework.web.method.support.ModelAndViewContainer; 12 | 13 | @RequiredArgsConstructor 14 | @Component 15 | public class LoginUserArgumentResolver implements HandlerMethodArgumentResolver { 16 | 17 | private final LoginService loginService; 18 | 19 | @Override 20 | public boolean supportsParameter(MethodParameter parameter) { 21 | return parameter.hasParameterAnnotation(CurrentUser.class); 22 | } 23 | 24 | @Override 25 | public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, 26 | NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { 27 | return loginService.getLoginUser(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/global/config/WebConfig.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.global.config; 2 | 3 | import com.flab.modu.global.interceptor.LoginCheckInterceptor; 4 | import com.flab.modu.product.converter.ProductStatusCodeRequestConverter; 5 | import org.springframework.format.FormatterRegistry; 6 | import java.util.List; 7 | import lombok.RequiredArgsConstructor; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.web.method.support.HandlerMethodArgumentResolver; 10 | import org.springframework.web.servlet.config.annotation.InterceptorRegistry; 11 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 12 | 13 | @RequiredArgsConstructor 14 | @Configuration 15 | public class WebConfig implements WebMvcConfigurer { 16 | 17 | private final LoginCheckInterceptor loginCheckInterceptor; 18 | 19 | private final ProductStatusCodeRequestConverter productStatusCodeRequestConverter; 20 | 21 | private final LoginUserArgumentResolver loginUserArgumentResolver; 22 | 23 | @Override 24 | public void addInterceptors(InterceptorRegistry registry) { 25 | registry.addInterceptor(loginCheckInterceptor); 26 | } 27 | 28 | @Override 29 | public void addFormatters(FormatterRegistry registry) { 30 | registry.addConverter(productStatusCodeRequestConverter); 31 | } 32 | 33 | @Override 34 | public void addArgumentResolvers(List resolvers) { 35 | resolvers.add(loginUserArgumentResolver); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/global/domain/BaseTimeEntity.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.global.domain; 2 | 3 | import java.time.LocalDateTime; 4 | import javax.persistence.Column; 5 | import javax.persistence.EntityListeners; 6 | import javax.persistence.MappedSuperclass; 7 | import lombok.Getter; 8 | import org.springframework.data.annotation.CreatedDate; 9 | import org.springframework.data.annotation.LastModifiedDate; 10 | import org.springframework.data.jpa.domain.support.AuditingEntityListener; 11 | import org.springframework.format.annotation.DateTimeFormat; 12 | 13 | @Getter 14 | @MappedSuperclass 15 | @EntityListeners(AuditingEntityListener.class) 16 | public class BaseTimeEntity { 17 | 18 | @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) 19 | @CreatedDate 20 | @Column(nullable = false, updatable = false) 21 | private LocalDateTime createdAt; 22 | 23 | @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) 24 | @LastModifiedDate 25 | @Column(nullable = false) 26 | private LocalDateTime modifiedAt; 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/global/exception/GlobalExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.global.exception; 2 | 3 | import com.flab.modu.global.response.ErrorResponseDto; 4 | import com.flab.modu.order.exception.OrderFailureException; 5 | import com.flab.modu.product.exception.InsufficientStockException; 6 | import com.flab.modu.product.exception.NotExistProductException; 7 | import com.flab.modu.users.exception.DuplicatedEmailException; 8 | import com.flab.modu.users.exception.NotExistedUserException; 9 | import com.flab.modu.users.exception.UnauthenticatedUserException; 10 | import com.flab.modu.users.exception.WrongPasswordException; 11 | import lombok.extern.slf4j.Slf4j; 12 | import org.springframework.http.HttpStatus; 13 | import org.springframework.http.ResponseEntity; 14 | import org.springframework.web.bind.MethodArgumentNotValidException; 15 | import org.springframework.web.bind.annotation.ExceptionHandler; 16 | import org.springframework.web.bind.annotation.RestControllerAdvice; 17 | import org.springframework.web.server.ResponseStatusException; 18 | 19 | @Slf4j 20 | @RestControllerAdvice 21 | public class GlobalExceptionHandler { 22 | 23 | @ExceptionHandler(DuplicatedEmailException.class) 24 | public final ResponseEntity handleDuplicatedEmailException( 25 | DuplicatedEmailException exception) { 26 | log.debug("중복된 이메일입니다.", exception); 27 | 28 | return new ResponseEntity<>("이미 가입된 이메일입니다.", HttpStatus.CONFLICT); 29 | } 30 | 31 | @ExceptionHandler(NotExistedUserException.class) 32 | public final ResponseEntity handleNotExistedUserException( 33 | NotExistedUserException exception) { 34 | log.debug("해당 이메일, 패스워드에 일치하는 사용자가 없습니다.", exception); 35 | 36 | return new ResponseEntity<>(exception.getMessage(), HttpStatus.UNAUTHORIZED); 37 | } 38 | 39 | @ExceptionHandler(UnauthenticatedUserException.class) 40 | public final ResponseEntity handleUnauthenticatedUserException( 41 | UnauthenticatedUserException exception) { 42 | log.debug("인증되지 않은 사용자입니다.", exception); 43 | 44 | return new ResponseEntity<>(exception.getMessage(), HttpStatus.UNAUTHORIZED); 45 | } 46 | 47 | @ExceptionHandler(WrongPasswordException.class) 48 | public final ResponseEntity handleWrongPasswordException( 49 | WrongPasswordException exception) { 50 | log.debug(exception.getMessage(), exception); 51 | 52 | return new ResponseEntity<>(exception.getMessage(), HttpStatus.UNAUTHORIZED); 53 | } 54 | 55 | @ExceptionHandler({MethodArgumentNotValidException.class}) 56 | public ResponseEntity errorHandler(MethodArgumentNotValidException e) { 57 | return new ResponseEntity( 58 | new ErrorResponseDto(e.getAllErrors().get(0).getDefaultMessage()), 59 | HttpStatus.BAD_REQUEST); 60 | } 61 | 62 | @ExceptionHandler(InsufficientStockException.class) 63 | public final ResponseStatusException handleInsufficientStockException( 64 | InsufficientStockException exception) { 65 | log.debug(exception.getMessage(), exception); 66 | 67 | return new ResponseStatusException(HttpStatus.BAD_REQUEST, exception.getMessage()); 68 | } 69 | 70 | @ExceptionHandler(OrderFailureException.class) 71 | public final ResponseStatusException handleOrderFailureException( 72 | OrderFailureException exception) { 73 | log.debug(exception.getMessage(), exception); 74 | 75 | return new ResponseStatusException(HttpStatus.BAD_REQUEST, exception.getMessage()); 76 | } 77 | 78 | @ExceptionHandler(NotExistProductException.class) 79 | public final ResponseStatusException handleNotExistProductException( 80 | NotExistProductException exception) { 81 | log.debug(exception.getMessage(), exception); 82 | 83 | return new ResponseStatusException(HttpStatus.BAD_REQUEST, exception.getMessage()); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/global/interceptor/LoginCheckInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.global.interceptor; 2 | 3 | import com.flab.modu.global.annotation.LoginCheck; 4 | import com.flab.modu.users.exception.UnauthenticatedUserException; 5 | import com.flab.modu.users.service.LoginService; 6 | import java.util.Arrays; 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | import lombok.RequiredArgsConstructor; 10 | import org.springframework.core.env.Environment; 11 | import org.springframework.stereotype.Component; 12 | import org.springframework.web.method.HandlerMethod; 13 | import org.springframework.web.servlet.HandlerInterceptor; 14 | 15 | @RequiredArgsConstructor 16 | @Component 17 | public class LoginCheckInterceptor implements HandlerInterceptor { 18 | 19 | private final Environment environment; 20 | private final LoginService loginService; 21 | 22 | @Override 23 | public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 24 | Object handler) { 25 | 26 | if (Arrays.stream(environment.getActiveProfiles()).anyMatch(e -> e.equals("test"))) { 27 | return true; 28 | } 29 | 30 | if (!(handler instanceof HandlerMethod)) { 31 | return true; 32 | } 33 | 34 | HandlerMethod handlerMethod = (HandlerMethod) handler; 35 | LoginCheck loginCheck = handlerMethod.getMethodAnnotation(LoginCheck.class); 36 | if (loginCheck == null) { 37 | return true; 38 | } 39 | 40 | if (loginService.getLoginUser() == null) { 41 | throw new UnauthenticatedUserException(); 42 | } 43 | 44 | return true; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/global/response/ErrorResponseDto.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.global.response; 2 | 3 | public class ErrorResponseDto { 4 | 5 | private String message; 6 | 7 | public ErrorResponseDto(String message) { 8 | this.message = message; 9 | } 10 | 11 | public String getMessage() { 12 | return message; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/market/controller/MarketController.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.market.controller; 2 | 3 | import com.flab.modu.market.domain.Market; 4 | import com.flab.modu.market.service.MarketService; 5 | import com.flab.modu.users.domain.common.UserConstant; 6 | import javax.servlet.http.HttpSession; 7 | import javax.validation.Valid; 8 | import lombok.RequiredArgsConstructor; 9 | import org.springframework.web.bind.annotation.PostMapping; 10 | import org.springframework.web.bind.annotation.RequestBody; 11 | import org.springframework.web.bind.annotation.RestController; 12 | import org.springframework.web.bind.annotation.SessionAttribute; 13 | 14 | @RequiredArgsConstructor 15 | @RestController 16 | public class MarketController { 17 | 18 | private final MarketService marketService; 19 | 20 | @PostMapping("/markets") 21 | public MarketDto.CreateResponse createMarket( 22 | @RequestBody @Valid MarketDto.CreateRequest createRequest, 23 | @SessionAttribute(value = UserConstant.EMAIL) String sellerId) { 24 | return marketService.createMarket(createRequest, sellerId); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/market/controller/MarketDto.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.market.controller; 2 | 3 | import com.flab.modu.market.domain.Market; 4 | import com.flab.modu.market.domain.MarketStatus; 5 | import java.time.LocalDateTime; 6 | import javax.validation.constraints.NotBlank; 7 | import javax.validation.constraints.Pattern; 8 | import lombok.Builder; 9 | import lombok.Getter; 10 | import lombok.NoArgsConstructor; 11 | import lombok.Setter; 12 | import org.hibernate.validator.constraints.Length; 13 | 14 | public class MarketDto { 15 | 16 | @Getter 17 | @NoArgsConstructor 18 | public static class CreateRequest { 19 | @NotBlank(message = "마켓명을 입력해주세요.") 20 | @Length(min = 1, max = 200, message = "마켓명은 1자 이상 200자 이하로 입력해주세요.") 21 | private String name; 22 | 23 | @NotBlank(message = "주소를 입력해주세요.") 24 | @Length(min = 1, max = 100, message = "주소는 1글자 이상 100자 이하로 입력해주세요.") 25 | @Pattern(regexp = "^[a-zA-Z]*$", message = "주소는 영어대소문자만 입력해주세요.") 26 | private String url; 27 | 28 | @Builder 29 | public CreateRequest(String name, String url) { 30 | this.name = name; 31 | this.url = url; 32 | } 33 | 34 | public Market toEntity(String sellerId) { 35 | return Market.builder() 36 | .sellerId(sellerId) 37 | .name(name) 38 | .url(url) 39 | .status(MarketStatus.ACTIVE) 40 | .build(); 41 | } 42 | } 43 | 44 | @Getter 45 | @Setter 46 | @NoArgsConstructor 47 | public static class CreateResponse { 48 | 49 | private Long id; 50 | private String sellerId; 51 | private String name; 52 | private String url; 53 | private LocalDateTime createdAt; 54 | private LocalDateTime modifiedAt; 55 | 56 | @Builder 57 | public CreateResponse(Market market) { 58 | this.id = market.getId(); 59 | this.sellerId = market.getSellerId(); 60 | this.name = market.getName(); 61 | this.url = market.getUrl(); 62 | this.createdAt = market.getCreatedAt(); 63 | this.modifiedAt = market.getModifiedAt(); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/market/domain/Market.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.market.domain; 2 | 3 | import com.flab.modu.global.domain.BaseTimeEntity; 4 | import java.time.LocalDateTime; 5 | import java.util.Objects; 6 | import javax.persistence.Column; 7 | import javax.persistence.Entity; 8 | import javax.persistence.EntityListeners; 9 | import javax.persistence.EnumType; 10 | import javax.persistence.Enumerated; 11 | import javax.persistence.GeneratedValue; 12 | import javax.persistence.GenerationType; 13 | import javax.persistence.Id; 14 | import javax.validation.constraints.NotNull; 15 | import lombok.AccessLevel; 16 | import lombok.Builder; 17 | import lombok.Getter; 18 | import lombok.NoArgsConstructor; 19 | import lombok.ToString; 20 | import org.springframework.data.annotation.CreatedDate; 21 | import org.springframework.data.annotation.LastModifiedDate; 22 | import org.springframework.data.jpa.domain.support.AuditingEntityListener; 23 | 24 | @Getter 25 | @ToString 26 | @NoArgsConstructor(access = AccessLevel.PROTECTED) 27 | @Entity 28 | public class Market extends BaseTimeEntity { 29 | 30 | @Id 31 | @GeneratedValue(strategy = GenerationType.IDENTITY) 32 | private Long id; 33 | 34 | @Column(nullable = false, length = 50) 35 | private String sellerId; 36 | 37 | @Column(nullable = false, length = 200) 38 | private String name; 39 | 40 | @Column(nullable = false) 41 | @Enumerated(EnumType.STRING) 42 | private MarketStatus status; 43 | 44 | @Column(nullable = false, length = 100) 45 | private String url; 46 | 47 | @Builder 48 | public Market(String sellerId, String name, String url, MarketStatus status) { 49 | this.sellerId = sellerId; 50 | this.name = name; 51 | this.url = url; 52 | this.status = status; 53 | } 54 | 55 | public void updateMarket(String name, String url, MarketStatus status){ 56 | this.name = name; 57 | this.url = url; 58 | this.status = status; 59 | } 60 | 61 | @Override 62 | public boolean equals(Object o) { 63 | if (this == o) { 64 | return true; 65 | } 66 | if (!(o instanceof Market)) { 67 | return false; 68 | } 69 | Market market = (Market) o; 70 | return id.equals(market.id); 71 | } 72 | 73 | @Override 74 | public int hashCode() { 75 | return Objects.hash(id); 76 | } 77 | 78 | 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/market/domain/MarketStatus.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.market.domain; 2 | 3 | public enum MarketStatus { 4 | ACTIVE, DISABLED; 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/market/exception/DuplicatedUrlException.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.market.exception; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.web.server.ResponseStatusException; 5 | 6 | public class DuplicatedUrlException extends ResponseStatusException { 7 | 8 | public DuplicatedUrlException() { 9 | super(HttpStatus.BAD_REQUEST, "중복된 마켓주소입니다."); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/market/exception/MarketNoPermissionException.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.market.exception; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.web.server.ResponseStatusException; 5 | 6 | public class MarketNoPermissionException extends ResponseStatusException { 7 | 8 | public MarketNoPermissionException() { 9 | super(HttpStatus.BAD_REQUEST, "잘못된 마켓정보입니다."); 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/market/exception/MarketNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.market.exception; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.web.server.ResponseStatusException; 5 | 6 | public class MarketNotFoundException extends ResponseStatusException { 7 | 8 | public MarketNotFoundException() { 9 | super(HttpStatus.BAD_REQUEST, "잘못된 마켓정보입니다."); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/market/repository/MarketRepository.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.market.repository; 2 | 3 | import com.flab.modu.market.domain.Market; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface MarketRepository extends JpaRepository { 7 | 8 | boolean existsByUrl(String url); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/market/service/MarketService.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.market.service; 2 | 3 | import com.flab.modu.market.controller.MarketDto; 4 | import com.flab.modu.market.domain.Market; 5 | import com.flab.modu.market.exception.DuplicatedUrlException; 6 | import com.flab.modu.market.repository.MarketRepository; 7 | import lombok.RequiredArgsConstructor; 8 | import org.springframework.stereotype.Service; 9 | 10 | @RequiredArgsConstructor 11 | @Service 12 | public class MarketService { 13 | 14 | private final MarketRepository marketRepository; 15 | 16 | public MarketDto.CreateResponse createMarket(MarketDto.CreateRequest createMarketRequest, 17 | String sellerId) { 18 | if (checkUrlDuplicate(createMarketRequest.getUrl())) { 19 | throw new DuplicatedUrlException(); 20 | } 21 | 22 | Market savedMarket = marketRepository.save(createMarketRequest.toEntity(sellerId)); 23 | return MarketDto.CreateResponse.builder().market(savedMarket).build(); 24 | } 25 | 26 | private boolean checkUrlDuplicate(String url) { 27 | return marketRepository.existsByUrl(url); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/order/controller/OrderController.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.order.controller; 2 | 3 | import com.flab.modu.global.annotation.CurrentUser; 4 | import com.flab.modu.global.annotation.LoginCheck; 5 | import com.flab.modu.order.service.OrderCallService; 6 | import javax.validation.Valid; 7 | import lombok.RequiredArgsConstructor; 8 | import org.springframework.http.HttpStatus; 9 | import org.springframework.web.bind.annotation.PostMapping; 10 | import org.springframework.web.bind.annotation.RequestBody; 11 | import org.springframework.web.bind.annotation.ResponseStatus; 12 | import org.springframework.web.bind.annotation.RestController; 13 | 14 | @RequiredArgsConstructor 15 | @RestController 16 | public class OrderController { 17 | 18 | private final OrderCallService orderCallService; 19 | 20 | @LoginCheck 21 | @PostMapping("/orders") 22 | @ResponseStatus(HttpStatus.CREATED) 23 | public Long createOrder(@RequestBody @Valid OrderDto.OrderRequest orderRequest, @CurrentUser String email) { 24 | return orderCallService.callOrder(orderRequest, email); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/order/controller/OrderDto.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.order.controller; 2 | 3 | import com.flab.modu.order.domain.common.OrderStatus; 4 | import com.flab.modu.order.domain.entity.Order; 5 | import com.flab.modu.users.domain.entity.User; 6 | import javax.validation.constraints.Min; 7 | import javax.validation.constraints.NotNull; 8 | import javax.validation.constraints.Pattern; 9 | import lombok.AccessLevel; 10 | import lombok.Builder; 11 | import lombok.Getter; 12 | import lombok.NoArgsConstructor; 13 | 14 | public class OrderDto { 15 | 16 | @Getter 17 | @NoArgsConstructor(access = AccessLevel.PROTECTED) 18 | public static class OrderRequest { 19 | 20 | @NotNull(message = "상품을 선택해주세요.") 21 | private Long productId; 22 | 23 | @Min(1) 24 | private int amount; 25 | 26 | private String deliveryMassage; 27 | 28 | @Pattern(regexp = "(01[016789])(\\d{3,4})(\\d{4})", message = "올바른 휴대폰 번호를 입력해주세요.") 29 | private String receiverTel; 30 | 31 | @Builder 32 | public OrderRequest(Long productId, int amount, String deliveryMassage, 33 | String receiverTel) { 34 | this.productId = productId; 35 | this.amount = amount; 36 | this.deliveryMassage = deliveryMassage; 37 | this.receiverTel = receiverTel; 38 | } 39 | 40 | public Order toEntity(User buyer) { 41 | return Order.builder() 42 | .buyer(buyer) 43 | .status(OrderStatus.PAYMENT_CONFIRMED) 44 | .deliveryMassage(deliveryMassage) 45 | .receiverTel(receiverTel) 46 | .build(); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/order/domain/common/OrderStatus.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.order.domain.common; 2 | 3 | public enum OrderStatus { 4 | 5 | PENDING_PAYMENT, 6 | PAYMENT_CONFIRMED, 7 | IN_PROCESS, 8 | START_SHIPPING, 9 | DELIVERED, 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/order/domain/entity/Order.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.order.domain.entity; 2 | 3 | import com.flab.modu.global.domain.BaseTimeEntity; 4 | import com.flab.modu.order.domain.common.OrderStatus; 5 | import com.flab.modu.users.domain.entity.User; 6 | import java.util.HashSet; 7 | import java.util.Set; 8 | import javax.persistence.CascadeType; 9 | import javax.persistence.Entity; 10 | import javax.persistence.EnumType; 11 | import javax.persistence.Enumerated; 12 | import javax.persistence.FetchType; 13 | import javax.persistence.GeneratedValue; 14 | import javax.persistence.GenerationType; 15 | import javax.persistence.Id; 16 | import javax.persistence.JoinColumn; 17 | import javax.persistence.Lob; 18 | import javax.persistence.ManyToOne; 19 | import javax.persistence.OneToMany; 20 | import javax.persistence.Table; 21 | import lombok.AccessLevel; 22 | import lombok.Builder; 23 | import lombok.Getter; 24 | import lombok.NoArgsConstructor; 25 | 26 | @Entity 27 | @Getter 28 | @NoArgsConstructor(access = AccessLevel.PROTECTED) 29 | @Table(name = "orders") 30 | public class Order extends BaseTimeEntity { 31 | 32 | @Id 33 | @GeneratedValue(strategy = GenerationType.IDENTITY) 34 | private Long id; 35 | 36 | @ManyToOne(fetch = FetchType.LAZY) 37 | @JoinColumn(name = "BUYER_ID") 38 | private User buyer; 39 | 40 | @Enumerated(EnumType.STRING) 41 | private OrderStatus status; 42 | 43 | @OneToMany(mappedBy = "order", orphanRemoval = true) 44 | private Set orderProducts = new HashSet<>(); 45 | 46 | @Lob 47 | private String deliveryMassage; 48 | 49 | private String receiverTel; 50 | 51 | @Builder 52 | public Order(Long id, User buyer, OrderStatus status, 53 | String deliveryMassage, String receiverTel) { 54 | this.id = id; 55 | this.buyer = buyer; 56 | this.status = status; 57 | this.deliveryMassage = deliveryMassage; 58 | this.receiverTel = receiverTel; 59 | } 60 | 61 | public void addProduct(OrderProduct product) { 62 | orderProducts.add(product); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/order/domain/entity/OrderProduct.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.order.domain.entity; 2 | 3 | import com.flab.modu.product.domain.entity.Product; 4 | import javax.persistence.Entity; 5 | import javax.persistence.GeneratedValue; 6 | import javax.persistence.Id; 7 | import javax.persistence.JoinColumn; 8 | import javax.persistence.ManyToOne; 9 | import lombok.AccessLevel; 10 | import lombok.Builder; 11 | import lombok.Getter; 12 | import lombok.NoArgsConstructor; 13 | 14 | @Entity 15 | @Getter 16 | @NoArgsConstructor(access = AccessLevel.PROTECTED) 17 | public class OrderProduct { 18 | 19 | @Id 20 | @GeneratedValue 21 | private Long id; 22 | 23 | @ManyToOne 24 | @JoinColumn(name = "ORDER_ID") 25 | private Order order; 26 | 27 | @ManyToOne 28 | @JoinColumn(name = "PRODUCT_ID") 29 | private Product product; 30 | 31 | private int amount; 32 | 33 | @Builder 34 | public OrderProduct(Long id, Order order, Product product, int amount) { 35 | this.id = id; 36 | this.order = order; 37 | this.product = product; 38 | this.amount = amount; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/order/exception/OrderFailureException.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.order.exception; 2 | 3 | public class OrderFailureException extends RuntimeException { 4 | 5 | private static final String MESSAGE= "상품 주문에 실패하였습니다."; 6 | 7 | public OrderFailureException(String message) { 8 | super(message); 9 | } 10 | 11 | public OrderFailureException(String message, Throwable cause) { 12 | super(message, cause); 13 | } 14 | 15 | public OrderFailureException() { 16 | super(MESSAGE); 17 | } 18 | 19 | public OrderFailureException(Throwable cause) { 20 | super(MESSAGE, cause); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/order/repository/OrderRepository.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.order.repository; 2 | 3 | import com.flab.modu.order.domain.entity.Order; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface OrderRepository extends JpaRepository { 7 | 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/order/service/OrderCallService.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.order.service; 2 | 3 | import com.flab.modu.order.controller.OrderDto; 4 | import com.flab.modu.order.exception.OrderFailureException; 5 | import lombok.RequiredArgsConstructor; 6 | import org.springframework.orm.ObjectOptimisticLockingFailureException; 7 | import org.springframework.stereotype.Service; 8 | 9 | @RequiredArgsConstructor 10 | @Service 11 | public class OrderCallService { 12 | 13 | private final OrderService orderService; 14 | 15 | public Long callOrder(OrderDto.OrderRequest orderRequest, String userEmail) { 16 | try { 17 | return orderService.createOrder(orderRequest, userEmail); 18 | } catch (ObjectOptimisticLockingFailureException e) { 19 | throw new OrderFailureException(); 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/order/service/OrderService.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.order.service; 2 | 3 | import com.flab.modu.order.controller.OrderDto; 4 | import com.flab.modu.order.domain.entity.Order; 5 | import com.flab.modu.order.domain.entity.OrderProduct; 6 | import com.flab.modu.order.repository.OrderRepository; 7 | import com.flab.modu.product.domain.entity.Product; 8 | import com.flab.modu.product.service.ProductService; 9 | import com.flab.modu.users.domain.entity.User; 10 | import com.flab.modu.users.exception.NotExistedUserException; 11 | import com.flab.modu.users.repository.UserRepository; 12 | import lombok.RequiredArgsConstructor; 13 | import lombok.extern.slf4j.Slf4j; 14 | import org.springframework.stereotype.Service; 15 | import org.springframework.transaction.annotation.Transactional; 16 | 17 | @Slf4j 18 | @RequiredArgsConstructor 19 | @Service 20 | public class OrderService { 21 | 22 | private final OrderRepository orderRepository; 23 | 24 | private final UserRepository userRepository; 25 | 26 | private final ProductService productService; 27 | 28 | @Transactional 29 | public Long createOrder(OrderDto.OrderRequest orderRequest, String userEmail) { 30 | 31 | User buyer = userRepository.findByEmail(userEmail) 32 | .orElseThrow(() -> new NotExistedUserException()); 33 | 34 | Order order = orderRequest.toEntity(buyer); 35 | 36 | Product product = productService.getProduct(orderRequest.getProductId()); 37 | 38 | productService.sellProduct(product, orderRequest.getAmount()); 39 | 40 | OrderProduct orderProduct = OrderProduct.builder() 41 | .order(order) 42 | .product(product) 43 | .amount(orderRequest.getAmount()) 44 | .build(); 45 | 46 | order.addProduct(orderProduct); 47 | 48 | return orderRepository.save(order).getId(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/product/controller/ProductController.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.product.controller; 2 | 3 | import com.flab.modu.product.service.ProductService; 4 | import com.flab.modu.users.domain.common.UserConstant; 5 | import javax.validation.Valid; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.http.MediaType; 8 | import org.springframework.web.bind.annotation.PostMapping; 9 | import org.springframework.web.bind.annotation.RequestPart; 10 | import org.springframework.web.bind.annotation.RestController; 11 | import org.springframework.web.bind.annotation.SessionAttribute; 12 | import org.springframework.web.multipart.MultipartFile; 13 | 14 | @RequiredArgsConstructor 15 | @RestController 16 | public class ProductController { 17 | 18 | private final ProductService productService; 19 | 20 | @PostMapping(value = "products", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE}) 21 | public ProductDto.CreateResponse createProduct( 22 | @RequestPart("product") @Valid ProductDto.CreateRequest createRequest, 23 | @RequestPart(value = "image",required = false) MultipartFile imageMultipartFile, 24 | @SessionAttribute(value = UserConstant.EMAIL) String sellerId) { 25 | return productService.createProduct(createRequest, imageMultipartFile, sellerId); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/product/controller/ProductDto.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.product.controller; 2 | 3 | import com.flab.modu.market.domain.Market; 4 | import com.flab.modu.product.domain.common.ProductStatus; 5 | import com.flab.modu.product.domain.entity.Product; 6 | import javax.validation.constraints.Max; 7 | import javax.validation.constraints.Min; 8 | import javax.validation.constraints.NotNull; 9 | import lombok.Builder; 10 | import lombok.Getter; 11 | import org.hibernate.validator.constraints.Length; 12 | 13 | public class ProductDto { 14 | 15 | @Getter 16 | public static class CreateRequest { 17 | 18 | @NotNull(message = "마켓아이디를 입력해주세요.") 19 | private Long marketId; 20 | 21 | @NotNull(message = "상품명을 입력해주세요.") 22 | @Length(min = 1, max = 200, message = "상품명 길이를 확인해주세요.") 23 | private String name; 24 | 25 | @NotNull(message = "재고를 입력해주세요.") 26 | @Min(value = 0, message = "재고를 1개 이상 입력해주세요.") 27 | @Max(value = 10_000, message = "재고를 10,000개 이하로 입력해주세요.") 28 | private Integer stock; 29 | 30 | @NotNull(message = "가격을 입력해주세요.") 31 | @Min(value = 0, message = "가격을 0원 이상 입력해주세요.") 32 | @Max(value = 100_000_000, message = "가격을 100,000,000원 이하로 입력해주세요.") 33 | private Integer price; 34 | 35 | @NotNull(message = "상품 상태를 입력해주세요.") 36 | private ProductStatus status; 37 | 38 | @Builder 39 | public CreateRequest(Long marketId, String name, Integer stock, Integer price, 40 | ProductStatus status) { 41 | this.marketId = marketId; 42 | this.name = name; 43 | this.stock = stock; 44 | this.price = price; 45 | this.status = status; 46 | } 47 | 48 | public Product toEntity(Market market, byte[] image) { 49 | return Product.builder().market(market) 50 | .stock(this.stock) 51 | .image(image) 52 | .name(this.name) 53 | .status(this.status) 54 | .price(this.price) 55 | .build(); 56 | } 57 | } 58 | 59 | @Getter 60 | public static class CreateResponse { 61 | 62 | private Long id; 63 | private Market market; 64 | private String name; 65 | private Integer price; 66 | private byte[] image; 67 | private Integer stock; 68 | private ProductStatus status; 69 | 70 | @Builder 71 | public CreateResponse(Product product) { 72 | this.id = product.getId(); 73 | this.name = product.getName(); 74 | this.price = product.getPrice(); 75 | this.image = product.getImage(); 76 | this.stock = product.getStock(); 77 | this.status = product.getStatus(); 78 | this.market = product.getMarket(); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/product/converter/ProductStatusCodeRequestConverter.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.product.converter; 2 | 3 | import com.flab.modu.product.domain.common.ProductStatus; 4 | import org.springframework.core.convert.converter.Converter; 5 | import org.springframework.stereotype.Component; 6 | 7 | @Component 8 | public class ProductStatusCodeRequestConverter implements Converter { 9 | 10 | @Override 11 | public ProductStatus convert(String code) { 12 | return ProductStatus.of(code); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/product/domain/common/ProductStatus.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.product.domain.common; 2 | 3 | import lombok.Getter; 4 | 5 | @Getter 6 | public enum ProductStatus { 7 | ACTIVE("ACTIVE"), DISABLE("DISABLE"); 8 | 9 | private String code; 10 | 11 | ProductStatus(String code) { 12 | this.code = code; 13 | } 14 | 15 | public static ProductStatus of(String code) { 16 | if (code == null) { 17 | throw new IllegalArgumentException(); 18 | } 19 | 20 | for (ProductStatus productStatus : ProductStatus.values()) { 21 | if (productStatus.code.equals(code)) { 22 | return productStatus; 23 | } 24 | } 25 | 26 | throw new IllegalArgumentException("일치하는 상품상태 코드가 없습니다."); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/product/domain/entity/Product.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.product.domain.entity; 2 | 3 | import com.flab.modu.global.domain.BaseTimeEntity; 4 | import com.flab.modu.market.domain.Market; 5 | import com.flab.modu.product.domain.common.ProductStatus; 6 | import javax.persistence.Column; 7 | import javax.persistence.Entity; 8 | import javax.persistence.EnumType; 9 | import javax.persistence.Enumerated; 10 | import javax.persistence.GeneratedValue; 11 | import javax.persistence.GenerationType; 12 | import javax.persistence.Id; 13 | import javax.persistence.Lob; 14 | import javax.persistence.ManyToOne; 15 | import javax.persistence.Version; 16 | import lombok.AccessLevel; 17 | import lombok.Builder; 18 | import lombok.Getter; 19 | import lombok.NoArgsConstructor; 20 | import lombok.ToString; 21 | 22 | @Getter 23 | @ToString 24 | @NoArgsConstructor(access = AccessLevel.PROTECTED) 25 | @Entity 26 | public class Product extends BaseTimeEntity { 27 | 28 | @Id 29 | @GeneratedValue(strategy = GenerationType.IDENTITY) 30 | private Long id; 31 | 32 | @ManyToOne(optional = false) 33 | private Market market; 34 | 35 | @Column(nullable = false, length = 200) 36 | private String name; 37 | 38 | @Column(nullable = false) 39 | private Integer stock; 40 | 41 | @Column(nullable = false) 42 | private Integer price; 43 | 44 | @Lob 45 | @Column(length = 10240) 46 | private byte[] image; 47 | 48 | @Enumerated(EnumType.STRING) 49 | private ProductStatus status; 50 | 51 | @Version 52 | private Long version; 53 | 54 | @Builder 55 | public Product(Market market, String name, Integer stock, Integer price, byte[] image, 56 | ProductStatus status) { 57 | this.market = market; 58 | this.name = name; 59 | this.stock = stock; 60 | this.price = price; 61 | this.image = image; 62 | this.status = status; 63 | } 64 | 65 | public void update(String name, Integer stock, Integer price, byte[] image, ProductStatus status){ 66 | this.name = name; 67 | this.stock = stock; 68 | this.price = price; 69 | this.image = image; 70 | this.status = status; 71 | } 72 | 73 | public void sell(int orderAmount) { 74 | this.stock -= orderAmount; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/product/exception/InsufficientStockException.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.product.exception; 2 | 3 | public class InsufficientStockException extends RuntimeException { 4 | 5 | private static final String MESSAGE= "상품의 재고가 부족합니다."; 6 | 7 | public InsufficientStockException() { 8 | super(MESSAGE); 9 | } 10 | 11 | public InsufficientStockException(String message) { 12 | super(message); 13 | } 14 | 15 | public InsufficientStockException(String message, Throwable cause) { 16 | super(message, cause); 17 | } 18 | 19 | public InsufficientStockException(Throwable cause) { 20 | super(MESSAGE, cause); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/product/exception/NotExistProductException.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.product.exception; 2 | 3 | public class NotExistProductException extends RuntimeException { 4 | 5 | private static final String MESSAGE= "존재하지 않는 상품입니다."; 6 | 7 | public NotExistProductException() { 8 | super(MESSAGE); 9 | } 10 | 11 | public NotExistProductException(Throwable cause) { 12 | super(MESSAGE, cause); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/product/exception/WrongImageDataException.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.product.exception; 2 | 3 | import org.springframework.http.HttpStatus; 4 | import org.springframework.web.server.ResponseStatusException; 5 | 6 | public class WrongImageDataException extends ResponseStatusException { 7 | 8 | public WrongImageDataException() { 9 | super(HttpStatus.BAD_REQUEST, "잘못된 이미지정보입니다."); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/product/repository/ProductRepository.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.product.repository; 2 | 3 | import com.flab.modu.product.domain.entity.Product; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface ProductRepository extends JpaRepository { 7 | 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/product/service/ProductService.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.product.service; 2 | 3 | import com.flab.modu.market.domain.Market; 4 | import com.flab.modu.market.exception.MarketNoPermissionException; 5 | import com.flab.modu.market.exception.MarketNotFoundException; 6 | import com.flab.modu.market.repository.MarketRepository; 7 | import com.flab.modu.product.controller.ProductDto; 8 | import com.flab.modu.product.controller.ProductDto.CreateRequest; 9 | import com.flab.modu.product.domain.entity.Product; 10 | import com.flab.modu.product.exception.InsufficientStockException; 11 | import com.flab.modu.product.exception.NotExistProductException; 12 | import com.flab.modu.product.exception.WrongImageDataException; 13 | import com.flab.modu.product.repository.ProductRepository; 14 | import java.io.IOException; 15 | import javax.transaction.Transactional; 16 | import lombok.RequiredArgsConstructor; 17 | import org.springframework.stereotype.Service; 18 | import org.springframework.web.multipart.MultipartFile; 19 | 20 | @RequiredArgsConstructor 21 | @Service 22 | public class ProductService { 23 | 24 | private final MarketRepository marketRepository; 25 | 26 | private final ProductRepository productRepository; 27 | 28 | public ProductDto.CreateResponse createProduct(ProductDto.CreateRequest createRequest, 29 | MultipartFile imageMultipartFile, String loginId) { 30 | 31 | Market market = checkCreatingProductParameterValidation(createRequest, loginId); 32 | 33 | Product savedProduct = saveProduct(market, createRequest, imageMultipartFile); 34 | 35 | return ProductDto.CreateResponse.builder().product(savedProduct).build(); 36 | } 37 | 38 | private Market checkCreatingProductParameterValidation(CreateRequest createRequest, 39 | String loginId) { 40 | Market market = marketRepository.findById(createRequest.getMarketId()) 41 | .orElseThrow(MarketNotFoundException::new); 42 | 43 | if (!checkMyMarket(market, loginId)) { 44 | throw new MarketNoPermissionException(); 45 | } 46 | return market; 47 | } 48 | 49 | private boolean checkMyMarket(Market market, String loginId) { 50 | if (!market.getSellerId().equals(loginId)) { 51 | return false; 52 | } 53 | 54 | return true; 55 | } 56 | 57 | private Product saveProduct(Market myMarket, CreateRequest createRequest, 58 | MultipartFile imageMultipartFile) { 59 | Product product = createRequest.toEntity(myMarket, getImageBinary(imageMultipartFile)); 60 | return productRepository.save(product); 61 | } 62 | 63 | private byte[] getImageBinary(MultipartFile imageMultipartFile) { 64 | try { 65 | if (imageMultipartFile == null) { 66 | return null; 67 | } else { 68 | return imageMultipartFile.getBytes(); 69 | } 70 | } catch (IOException e) { 71 | throw new WrongImageDataException(); 72 | } 73 | } 74 | 75 | public Product getProduct(Long id) { 76 | return productRepository.findById(id) 77 | .orElseThrow(() -> new NotExistProductException()); 78 | } 79 | 80 | @Transactional 81 | public void sellProduct(Product product, int orderAmount) { 82 | checkStockAvailability(product.getStock(), orderAmount); 83 | 84 | product.sell(orderAmount); 85 | } 86 | 87 | private void checkStockAvailability(int productStock, int orderAmount) { 88 | if (productStock < 1) { 89 | throw new InsufficientStockException("상품의 재고가 부족합니다."); 90 | } 91 | 92 | if (productStock < orderAmount) { 93 | throw new InsufficientStockException("주문 수량이 상품의 재고보다 많습니다."); 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/users/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.users.controller; 2 | 3 | import com.flab.modu.global.annotation.CurrentUser; 4 | import com.flab.modu.global.annotation.LoginCheck; 5 | import com.flab.modu.users.controller.UserDto.LoginRequest; 6 | import com.flab.modu.users.service.LoginService; 7 | import com.flab.modu.users.service.UserService; 8 | import javax.validation.Valid; 9 | import lombok.RequiredArgsConstructor; 10 | import org.springframework.http.HttpStatus; 11 | import org.springframework.web.bind.annotation.DeleteMapping; 12 | import org.springframework.web.bind.annotation.GetMapping; 13 | import org.springframework.web.bind.annotation.PostMapping; 14 | import org.springframework.web.bind.annotation.RequestBody; 15 | import org.springframework.web.bind.annotation.ResponseStatus; 16 | import org.springframework.web.bind.annotation.RestController; 17 | 18 | @RequiredArgsConstructor 19 | @RestController 20 | public class UserController { 21 | 22 | private final UserService userService; 23 | 24 | private final LoginService loginService; 25 | 26 | @PostMapping("/users") 27 | @ResponseStatus(HttpStatus.CREATED) 28 | public void createUser(@RequestBody @Valid UserDto.CreateRequest createRequest) { 29 | userService.createUser(createRequest); 30 | } 31 | 32 | @LoginCheck 33 | @DeleteMapping("/users") 34 | public void userWithdrawal(@RequestBody @Valid UserDto.PasswordRequest requestDto, 35 | @CurrentUser String email) { 36 | String password = requestDto.getPassword(); 37 | userService.delete(email, password); 38 | loginService.logout(); 39 | } 40 | 41 | @PostMapping("/users/login") 42 | public void login(@RequestBody @Valid UserDto.LoginRequest loginRequest) { 43 | loginService.login(loginRequest); 44 | } 45 | 46 | @LoginCheck 47 | @DeleteMapping("/users/logout") 48 | public void logout() { 49 | loginService.logout(); 50 | } 51 | 52 | @GetMapping("/users/session") 53 | public String getUserInfo(LoginRequest loginRequest) { 54 | return loginService.getLoginUser(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/users/controller/UserDto.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.users.controller; 2 | 3 | import com.flab.modu.users.domain.common.UserRole; 4 | import com.flab.modu.users.domain.entity.User; 5 | import com.flab.modu.users.encoder.PasswordEncoder; 6 | import javax.validation.constraints.Email; 7 | import javax.validation.constraints.NotBlank; 8 | import javax.validation.constraints.Pattern; 9 | import javax.validation.constraints.Size; 10 | import lombok.AccessLevel; 11 | import lombok.Builder; 12 | import lombok.Getter; 13 | import lombok.NoArgsConstructor; 14 | import lombok.ToString; 15 | 16 | public class UserDto { 17 | 18 | @Getter 19 | @NoArgsConstructor(access = AccessLevel.PROTECTED) 20 | public static class CreateRequest { 21 | 22 | @NotBlank(message = "이메일 주소를 입력해주세요.") 23 | @Email(message = "올바른 이메일 주소를 입력해주세요.") 24 | private String email; 25 | 26 | @NotBlank(message = "비밀번호를 입력해주세요.") 27 | @Size(min = 8, max = 20, message = "비밀번호는 8자 이상 20자 이하로 입력해주세요.") 28 | private String password; 29 | 30 | @NotBlank(message = "이름을 입력해주세요.") 31 | @Size(min = 2, max = 10, message = "이름은 2자 이상 10자 이하로 입력해주세요.") 32 | private String name; 33 | 34 | @NotBlank(message = "휴대폰 번호를 입력해주세요.") 35 | @Pattern(regexp = "(01[016789])(\\d{3,4})(\\d{4})", message = "올바른 휴대폰 번호를 입력해주세요.") 36 | private String phoneNumber; 37 | 38 | @Builder 39 | public CreateRequest(String email, String password, String name, String phoneNumber) { 40 | this.email = email; 41 | this.password = password; 42 | this.name = name; 43 | this.phoneNumber = phoneNumber; 44 | } 45 | 46 | public User toEntity() { 47 | return User.builder() 48 | .email(email) 49 | .password(password) 50 | .name(name) 51 | .role(UserRole.BUYER) 52 | .phoneNumber(phoneNumber) 53 | .build(); 54 | } 55 | 56 | public void encryptPassword(PasswordEncoder passwordEncoder) { 57 | String encryption = passwordEncoder.encrypt(this.password); 58 | this.password = encryption; 59 | } 60 | } 61 | 62 | @Getter 63 | @NoArgsConstructor(access = AccessLevel.PROTECTED) 64 | public static class LoginRequest { 65 | 66 | @NotBlank(message = "이메일 주소를 입력해주세요.") 67 | @Email(message = "올바른 이메일 주소를 입력해주세요.") 68 | private String email; 69 | 70 | @NotBlank(message = "비밀번호를 입력해주세요.") 71 | @Size(min = 8, max = 20, message = "비밀번호는 8자 이상 20자 이하로 입력해주세요.") 72 | private String password; 73 | 74 | @Builder 75 | public LoginRequest(String email, String password) { 76 | this.email = email; 77 | this.password = password; 78 | } 79 | 80 | public void encryptPassword(PasswordEncoder passwordEncoder) { 81 | String encryption = passwordEncoder.encrypt(this.password); 82 | this.password = encryption; 83 | } 84 | } 85 | 86 | @Getter 87 | @NoArgsConstructor(access = AccessLevel.PROTECTED) 88 | public static class PasswordRequest { 89 | 90 | @NotBlank(message = "비밀번호를 입력해주세요.") 91 | @Size(min = 8, max = 20, message = "비밀번호는 8자 이상 20자 이하로 입력해주세요.") 92 | private String password; 93 | 94 | @Builder 95 | public PasswordRequest(String password) { 96 | this.password = password; 97 | } 98 | } 99 | 100 | @Getter 101 | @NoArgsConstructor 102 | public static class UserResponse { 103 | 104 | private Long id; 105 | 106 | private String email; 107 | 108 | private String name; 109 | 110 | private UserRole role; 111 | 112 | private String phoneNumber; 113 | 114 | @Builder 115 | public UserResponse(Long id, String email, String name, UserRole role, 116 | String phoneNumber) { 117 | this.id = id; 118 | this.email = email; 119 | this.name = name; 120 | this.role = role; 121 | this.phoneNumber = phoneNumber; 122 | } 123 | } 124 | 125 | @Getter 126 | @NoArgsConstructor(access = AccessLevel.PROTECTED) 127 | public static class UserSearchCondition { 128 | 129 | private Long id; 130 | 131 | private String email; 132 | 133 | private String name; 134 | 135 | private UserRole role; 136 | 137 | private String phoneNumber; 138 | 139 | @Builder 140 | public UserSearchCondition(Long id, String email, String name, UserRole role, 141 | String phoneNumber) { 142 | this.id = id; 143 | this.email = email; 144 | this.name = name; 145 | this.role = role; 146 | this.phoneNumber = phoneNumber; 147 | } 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/users/domain/common/UserConstant.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.users.domain.common; 2 | 3 | import lombok.Getter; 4 | 5 | public class UserConstant { 6 | 7 | public static final String EMAIL = "email"; 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/users/domain/common/UserRole.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.users.domain.common; 2 | 3 | public enum UserRole { 4 | BUYER, SELLER, ADMIN; 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/users/domain/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.users.domain.entity; 2 | 3 | import com.flab.modu.global.domain.BaseTimeEntity; 4 | import com.flab.modu.users.domain.common.UserRole; 5 | import javax.persistence.Column; 6 | import javax.persistence.Entity; 7 | import javax.persistence.EnumType; 8 | import javax.persistence.Enumerated; 9 | import javax.persistence.GeneratedValue; 10 | import javax.persistence.GenerationType; 11 | import javax.persistence.Id; 12 | import javax.persistence.Table; 13 | import lombok.AccessLevel; 14 | import lombok.Builder; 15 | import lombok.Getter; 16 | import lombok.NoArgsConstructor; 17 | 18 | @Entity 19 | @Getter 20 | @NoArgsConstructor(access = AccessLevel.PROTECTED) 21 | @Table(name = "users") 22 | public class User extends BaseTimeEntity { 23 | @Id 24 | @GeneratedValue(strategy = GenerationType.IDENTITY) 25 | private Long id; 26 | 27 | @Column(nullable = false) 28 | private String email; 29 | 30 | @Column(nullable = false) 31 | private String name; 32 | 33 | @Column(nullable = false) 34 | private String password; 35 | 36 | @Enumerated(EnumType.STRING) 37 | private UserRole role; 38 | 39 | private String phoneNumber; 40 | 41 | @Builder 42 | public User(Long id, String email, String name, String password, UserRole role, String phoneNumber) { 43 | this.id = id; 44 | this.email = email; 45 | this.name = name; 46 | this.password = password; 47 | this.role = role; 48 | this.phoneNumber = phoneNumber; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/users/encoder/PasswordEncoder.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.users.encoder; 2 | 3 | import java.io.UnsupportedEncodingException; 4 | import java.nio.charset.StandardCharsets; 5 | import java.security.MessageDigest; 6 | import java.security.NoSuchAlgorithmException; 7 | import java.security.spec.InvalidKeySpecException; 8 | import java.security.spec.KeySpec; 9 | import java.util.Base64; 10 | import javax.crypto.SecretKeyFactory; 11 | import javax.crypto.spec.PBEKeySpec; 12 | import org.springframework.stereotype.Component; 13 | 14 | @Component 15 | public class PasswordEncoder { 16 | 17 | public String encrypt(String password) { 18 | try { 19 | KeySpec spec = new PBEKeySpec(password.toCharArray(), getSalt(password), 65536, 128); 20 | SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); 21 | 22 | byte[] hash = factory.generateSecret(spec).getEncoded(); 23 | return Base64.getEncoder().encodeToString(hash); 24 | } catch (NoSuchAlgorithmException | UnsupportedEncodingException | 25 | InvalidKeySpecException e) { 26 | throw new RuntimeException(e); 27 | } 28 | } 29 | 30 | private byte[] getSalt(String password) 31 | throws NoSuchAlgorithmException, UnsupportedEncodingException { 32 | 33 | MessageDigest digest = MessageDigest.getInstance("SHA-512"); 34 | byte[] keyBytes = password.getBytes("UTF-8"); 35 | 36 | return digest.digest(keyBytes); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/users/exception/DuplicatedEmailException.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.users.exception; 2 | 3 | public class DuplicatedEmailException extends IllegalArgumentException { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/users/exception/NotExistedUserException.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.users.exception; 2 | 3 | public class NotExistedUserException 4 | extends IllegalArgumentException { 5 | 6 | private static final String MESSAGE = "아이디나 패스워드를 확인해주세요."; 7 | 8 | public NotExistedUserException() { 9 | super(MESSAGE); 10 | } 11 | 12 | public NotExistedUserException(Throwable cause) { 13 | super(MESSAGE, cause); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/users/exception/UnauthenticatedUserException.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.users.exception; 2 | 3 | public class UnauthenticatedUserException extends RuntimeException { 4 | 5 | private static final String MESSAGE = "인증되지 않은 사용자입니다."; 6 | 7 | public UnauthenticatedUserException() { 8 | super(MESSAGE); 9 | } 10 | 11 | public UnauthenticatedUserException(Throwable cause) { 12 | super(MESSAGE, cause); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/users/exception/WrongPasswordException.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.users.exception; 2 | 3 | public class WrongPasswordException extends RuntimeException { 4 | 5 | private static final String MESSAGE = "잘못된 비밀번호입니다."; 6 | 7 | public WrongPasswordException() { 8 | super(MESSAGE); 9 | } 10 | 11 | public WrongPasswordException(Throwable cause) { 12 | super(MESSAGE, cause); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/users/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.users.repository; 2 | 3 | import com.flab.modu.users.controller.UserDto.UserResponse; 4 | import com.flab.modu.users.controller.UserDto.UserSearchCondition; 5 | import com.flab.modu.users.domain.entity.User; 6 | import java.util.Optional; 7 | import org.springframework.data.domain.Page; 8 | import org.springframework.data.domain.Pageable; 9 | import org.springframework.data.jpa.repository.JpaRepository; 10 | 11 | public interface UserRepository extends JpaRepository, UserRepositoryCustom { 12 | 13 | boolean existsByEmail(String email); 14 | 15 | Optional findByEmailAndPassword(String email, String password); 16 | 17 | void deleteByEmail(String email); 18 | 19 | Optional findByEmail(String email); 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/users/repository/UserRepositoryCustom.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.users.repository; 2 | 3 | import com.flab.modu.users.controller.UserDto.UserResponse; 4 | import com.flab.modu.users.controller.UserDto.UserSearchCondition; 5 | import org.springframework.data.domain.Page; 6 | import org.springframework.data.domain.Pageable; 7 | 8 | public interface UserRepositoryCustom { 9 | 10 | Page searchByUsers(UserSearchCondition condition, Pageable pageable); 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/users/repository/UserRepositoryImpl.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.users.repository; 2 | 3 | import static com.flab.modu.users.domain.entity.QUser.user; 4 | import static org.springframework.util.StringUtils.hasText; 5 | 6 | import com.flab.modu.users.controller.UserDto.UserResponse; 7 | import com.flab.modu.users.controller.UserDto.UserSearchCondition; 8 | import com.flab.modu.users.domain.common.UserRole; 9 | import com.querydsl.core.types.Projections; 10 | import com.querydsl.core.types.dsl.BooleanExpression; 11 | import com.querydsl.jpa.impl.JPAQueryFactory; 12 | import java.util.List; 13 | import lombok.RequiredArgsConstructor; 14 | import org.springframework.data.domain.Page; 15 | import org.springframework.data.domain.PageImpl; 16 | import org.springframework.data.domain.Pageable; 17 | 18 | @RequiredArgsConstructor 19 | public class UserRepositoryImpl implements UserRepositoryCustom { 20 | 21 | private final JPAQueryFactory jpaQueryFactory; 22 | 23 | @Override 24 | public Page searchByUsers(UserSearchCondition searchRequest, Pageable pageable) { 25 | 26 | List users = getUsers(searchRequest, pageable); 27 | 28 | Long count = getCount(searchRequest); 29 | 30 | return new PageImpl<>(users, pageable, count); 31 | } 32 | 33 | private List getUsers(UserSearchCondition searchRequest, Pageable pageable) { 34 | return jpaQueryFactory 35 | .select(Projections.fields(UserResponse.class, 36 | user.id, 37 | user.email, 38 | user.name, 39 | user.role, 40 | user.role, 41 | user.phoneNumber)) 42 | .from(user) 43 | .where( 44 | userIdEq(searchRequest.getId()), 45 | userEmailEq(searchRequest.getEmail()), 46 | userNameEq(searchRequest.getName()), 47 | userRoleEq(searchRequest.getRole()), 48 | userPhoneEq(searchRequest.getPhoneNumber()) 49 | ) 50 | .offset(pageable.getOffset()) 51 | .limit(pageable.getPageSize()) 52 | .fetch(); 53 | } 54 | 55 | private Long getCount(UserSearchCondition searchRequest) { 56 | return jpaQueryFactory.select(user.count()) 57 | .from(user) 58 | .where( 59 | userIdEq(searchRequest.getId()), 60 | userEmailEq(searchRequest.getEmail()), 61 | userNameEq(searchRequest.getName()), 62 | userRoleEq(searchRequest.getRole()), 63 | userPhoneEq(searchRequest.getPhoneNumber()) 64 | ) 65 | .fetchOne(); 66 | } 67 | 68 | private BooleanExpression userIdEq(Long userId) { 69 | return userId != null ? user.id.eq(userId) : null; 70 | } 71 | 72 | private BooleanExpression userEmailEq(String userEmail) { 73 | return hasText(userEmail) ? user.email.contains(userEmail) : null; 74 | } 75 | 76 | private BooleanExpression userNameEq(String userName) { 77 | return hasText(userName) ? user.name.contains(userName) : null; 78 | } 79 | 80 | private BooleanExpression userRoleEq(UserRole userRole) { 81 | return userRole != null ? user.role.eq(userRole) : null; 82 | } 83 | 84 | private BooleanExpression userPhoneEq(String userPhoneNumber) { 85 | return hasText(userPhoneNumber) ? user.phoneNumber.contains(userPhoneNumber) : null; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/users/service/LoginService.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.users.service; 2 | 3 | import static com.flab.modu.users.domain.common.UserConstant.EMAIL; 4 | 5 | import com.flab.modu.users.controller.UserDto; 6 | import com.flab.modu.users.domain.entity.User; 7 | import com.flab.modu.users.encoder.PasswordEncoder; 8 | import com.flab.modu.users.exception.NotExistedUserException; 9 | import com.flab.modu.users.repository.UserRepository; 10 | import javax.servlet.http.HttpSession; 11 | import lombok.RequiredArgsConstructor; 12 | import org.springframework.stereotype.Service; 13 | 14 | @RequiredArgsConstructor 15 | @Service 16 | public class LoginService { 17 | 18 | private final HttpSession session; 19 | 20 | private final UserRepository userRepository; 21 | 22 | private final PasswordEncoder passwordEncoder; 23 | 24 | public void login(UserDto.LoginRequest loginRequest) { 25 | loginRequest.encryptPassword(passwordEncoder); 26 | User findUser = userRepository.findByEmailAndPassword(loginRequest.getEmail(), 27 | loginRequest.getPassword()) 28 | .orElseThrow(NotExistedUserException::new); 29 | 30 | session.setAttribute(EMAIL, findUser.getEmail()); 31 | } 32 | 33 | public void logout() { 34 | session.invalidate(); 35 | } 36 | 37 | public String getLoginUser() { 38 | return (String) session.getAttribute(EMAIL); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/flab/modu/users/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.users.service; 2 | 3 | import com.flab.modu.users.controller.UserDto; 4 | import com.flab.modu.users.encoder.PasswordEncoder; 5 | import com.flab.modu.users.exception.DuplicatedEmailException; 6 | import com.flab.modu.users.exception.NotExistedUserException; 7 | import com.flab.modu.users.exception.WrongPasswordException; 8 | import com.flab.modu.users.repository.UserRepository; 9 | import lombok.RequiredArgsConstructor; 10 | import lombok.extern.slf4j.Slf4j; 11 | import org.springframework.stereotype.Service; 12 | import org.springframework.transaction.annotation.Transactional; 13 | 14 | @Slf4j 15 | @RequiredArgsConstructor 16 | @Service 17 | public class UserService { 18 | 19 | private final UserRepository userRepository; 20 | 21 | private final PasswordEncoder passwordEncoder; 22 | 23 | public void createUser(UserDto.CreateRequest createRequest) { 24 | if (checkEmailDuplicate(createRequest.getEmail())) { 25 | throw new DuplicatedEmailException(); 26 | } 27 | createRequest.encryptPassword(passwordEncoder); 28 | 29 | userRepository.save(createRequest.toEntity()); 30 | } 31 | 32 | public boolean checkEmailDuplicate(String email) { 33 | return userRepository.existsByEmail(email); 34 | } 35 | 36 | @Transactional 37 | public void delete(String email, String password) { 38 | if (!checkEmailDuplicate(email)) { 39 | new NotExistedUserException(); 40 | } 41 | 42 | userRepository.findByEmailAndPassword(email, passwordEncoder.encrypt(password)) 43 | .orElseThrow(() -> new WrongPasswordException()); 44 | 45 | userRepository.deleteByEmail(email); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/resources/application-product.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | url: ${DB_URL} 4 | username: ${DB_USERNAME} 5 | password: ${DB_PASSWORD} 6 | driver-class-name: com.mysql.cj.jdbc.Driver 7 | jpa: 8 | hibernate: 9 | ddl-auto: none 10 | database: mysql 11 | database-platform: org.hibernate.dialect.MySQL5InnoDBDialect 12 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | url: jdbc:h2:tcp://localhost/~/modu 4 | username: sa 5 | password: 6 | driver-class-name: org.h2.Driver 7 | jpa: 8 | hibernate: 9 | ddl-auto: none 10 | properties: 11 | hibernate.format_sql: true 12 | show-sql: true 13 | logging: 14 | level: 15 | com.flab.modu: debug 16 | org.springframework.jdbc: DEBUG 17 | -------------------------------------------------------------------------------- /src/test/java/com/flab/modu/ModuUiMarketApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class ModuUiMarketApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/test/java/com/flab/modu/admin/controller/AdminControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.admin.controller; 2 | 3 | import static org.mockito.ArgumentMatchers.any; 4 | import static org.mockito.BDDMockito.given; 5 | import static org.mockito.BDDMockito.then; 6 | import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; 7 | import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; 8 | import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; 9 | import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; 10 | import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; 11 | import static org.springframework.restdocs.request.RequestDocumentation.requestParameters; 12 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 13 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 14 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 15 | 16 | import com.fasterxml.jackson.databind.ObjectMapper; 17 | import com.flab.modu.admin.service.AdminService; 18 | import com.flab.modu.users.controller.UserDto.UserResponse; 19 | import com.flab.modu.users.domain.common.UserRole; 20 | import com.flab.modu.users.service.LoginService; 21 | import java.util.List; 22 | import java.util.stream.Collectors; 23 | import java.util.stream.IntStream; 24 | import org.junit.jupiter.api.BeforeAll; 25 | import org.junit.jupiter.api.DisplayName; 26 | import org.junit.jupiter.api.Test; 27 | import org.junit.jupiter.api.extension.ExtendWith; 28 | import org.springframework.beans.factory.annotation.Autowired; 29 | import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; 30 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 31 | import org.springframework.boot.test.mock.mockito.MockBean; 32 | import org.springframework.data.domain.PageImpl; 33 | import org.springframework.data.domain.PageRequest; 34 | import org.springframework.data.domain.Pageable; 35 | import org.springframework.restdocs.RestDocumentationExtension; 36 | import org.springframework.restdocs.payload.JsonFieldType; 37 | import org.springframework.test.web.servlet.MockMvc; 38 | import org.springframework.util.LinkedMultiValueMap; 39 | import org.springframework.util.MultiValueMap; 40 | 41 | @ExtendWith(RestDocumentationExtension.class) 42 | @AutoConfigureRestDocs 43 | @WebMvcTest(AdminController.class) 44 | class AdminControllerTest { 45 | 46 | @MockBean 47 | private AdminService adminService; 48 | 49 | @MockBean 50 | private LoginService loginService; 51 | 52 | @Autowired 53 | private MockMvc mockMvc; 54 | 55 | @Autowired 56 | private ObjectMapper objectMapper; 57 | 58 | private static List userResponseList; 59 | 60 | private static final int USERS_SIZE = 10; 61 | 62 | @BeforeAll 63 | static void init() { 64 | userResponseList = IntStream.range(0, USERS_SIZE) 65 | .mapToObj(i -> getUserResponse(i)) 66 | .collect(Collectors.toList()); 67 | } 68 | 69 | private static UserResponse getUserResponse(int i) { 70 | return UserResponse.builder() 71 | .id((long) i) 72 | .email(getConcatData("test@modu.com", i)) 73 | .name(getConcatData("testName", i)) 74 | .phoneNumber(getConcatData("0100000000", i)) 75 | .role(UserRole.BUYER) 76 | .build(); 77 | } 78 | 79 | private static String getConcatData(String data, int i) { 80 | return new StringBuilder(data).append(i).toString(); 81 | } 82 | 83 | @Test 84 | @DisplayName("회원조회 - 회원 전체 조회에 성공한다.") 85 | public void findAllUsers_successful() throws Exception { 86 | // given 87 | Pageable pageable = getPageable(); 88 | PageImpl result = new PageImpl<>(userResponseList, pageable, 89 | USERS_SIZE); 90 | given(adminService.findUsers(any(), any())).willReturn(result); 91 | 92 | MultiValueMap queryString = new LinkedMultiValueMap<>(); 93 | queryString.add("page", "0"); 94 | queryString.add("size", "10"); 95 | 96 | // when 97 | mockMvc.perform(get("/admin/users") 98 | .params(queryString)) 99 | .andExpect(status().isOk()) 100 | .andExpect(jsonPath("$.content.[0].id").value(userResponseList.get(0).getId())) 101 | .andExpect(jsonPath("$.content.[0].email").value(userResponseList.get(0).getEmail())) 102 | .andExpect(jsonPath("$.content.[0].name").value(userResponseList.get(0).getName())) 103 | .andExpect( 104 | jsonPath("$.content.[0].role").value(userResponseList.get(0).getRole().toString())) 105 | .andExpect(jsonPath("$.content.[0].phoneNumber").value( 106 | userResponseList.get(0).getPhoneNumber())) 107 | .andExpect(jsonPath("$.content.[1].id").value(userResponseList.get(1).getId())) 108 | .andExpect(jsonPath("$.content.[1].email").value(userResponseList.get(1).getEmail())) 109 | .andExpect(jsonPath("$.content.[1].name").value(userResponseList.get(1).getName())) 110 | .andExpect( 111 | jsonPath("$.content.[1].role").value(userResponseList.get(1).getRole().toString())) 112 | .andExpect(jsonPath("$.content.[1].phoneNumber").value( 113 | userResponseList.get(1).getPhoneNumber())) 114 | .andExpect(jsonPath("$.totalElements").value(USERS_SIZE)) 115 | .andDo(print()) 116 | .andDo(document("admin/users/findAll", 117 | requestParameters( 118 | parameterWithName("page").description("페이지 번호"), 119 | parameterWithName("size").description("한 페이지 사이즈") 120 | ), 121 | responseFields( 122 | fieldWithPath("content.[].id").type(JsonFieldType.NUMBER).description("아이디"), 123 | fieldWithPath("content.[].email").type(JsonFieldType.STRING) 124 | .description("이메일"), 125 | fieldWithPath("content.[].name").type(JsonFieldType.STRING) 126 | .description("회원명"), 127 | fieldWithPath("content.[].role").type(JsonFieldType.STRING) 128 | .description("역할"), 129 | fieldWithPath("content.[].phoneNumber").type(JsonFieldType.STRING) 130 | .description("전화번호"), 131 | fieldWithPath("pageable.offset").ignored(), 132 | fieldWithPath("pageable.pageSize").ignored(), 133 | fieldWithPath("pageable.pageNumber").ignored(), 134 | fieldWithPath("pageable.paged").ignored(), 135 | fieldWithPath("pageable.unpaged").ignored(), 136 | fieldWithPath("pageable.sort.sorted").ignored(), 137 | fieldWithPath("pageable.sort.unsorted").ignored(), 138 | fieldWithPath("pageable.sort.empty").ignored(), 139 | fieldWithPath("sort.empty").ignored(), 140 | fieldWithPath("sort.sorted").ignored(), 141 | fieldWithPath("sort.unsorted").ignored(), 142 | fieldWithPath("totalPages").ignored(), 143 | fieldWithPath("size").ignored(), 144 | fieldWithPath("number").ignored(), 145 | fieldWithPath("first").ignored(), 146 | fieldWithPath("last").ignored(), 147 | fieldWithPath("numberOfElements").ignored(), 148 | fieldWithPath("empty").ignored(), 149 | fieldWithPath("totalElements").ignored() 150 | ) 151 | )); 152 | 153 | // then 154 | then(adminService).should().findUsers(any(), any()); 155 | } 156 | 157 | @Test 158 | @DisplayName("회원조회[이름] - 특정 회원 조회에 성공한다.") 159 | public void findUserByName_successful() throws Exception { 160 | // given 161 | Pageable pageable = getPageable(); 162 | int findIndex = 2; 163 | String name = userResponseList.get(findIndex).getName(); 164 | List list = getUserListByName(name); 165 | PageImpl result = new PageImpl<>(list, pageable, USERS_SIZE); 166 | given(adminService.findUsers(any(), any())).willReturn(result); 167 | 168 | MultiValueMap queryString = new LinkedMultiValueMap<>(); 169 | queryString.add("page", "0"); 170 | queryString.add("size", "10"); 171 | queryString.add("name", name); 172 | 173 | // when 174 | mockMvc.perform(get("/admin/users") 175 | .params(queryString)) 176 | .andExpect(status().isOk()) 177 | .andExpect(jsonPath("$.content.[0].id").value(userResponseList.get(findIndex).getId())) 178 | .andExpect(jsonPath("$.content.[0].email").value(userResponseList.get(findIndex).getEmail())) 179 | .andExpect(jsonPath("$.content.[0].name").value(userResponseList.get(findIndex).getName())) 180 | .andExpect( 181 | jsonPath("$.content.[0].role").value(userResponseList.get(findIndex).getRole().toString())) 182 | .andExpect(jsonPath("$.content.[0].phoneNumber").value( 183 | userResponseList.get(findIndex).getPhoneNumber())) 184 | .andDo(print()) 185 | .andDo(document("admin/users/findByName", 186 | requestParameters( 187 | parameterWithName("page").description("페이지 번호"), 188 | parameterWithName("size").description("한 페이지 사이즈"), 189 | parameterWithName("name").description("회원명") 190 | ), 191 | responseFields( 192 | fieldWithPath("content.[].id").type(JsonFieldType.NUMBER).description("아이디"), 193 | fieldWithPath("content.[].email").type(JsonFieldType.STRING) 194 | .description("이메일"), 195 | fieldWithPath("content.[].name").type(JsonFieldType.STRING) 196 | .description("회원명"), 197 | fieldWithPath("content.[].role").type(JsonFieldType.STRING) 198 | .description("역할"), 199 | fieldWithPath("content.[].phoneNumber").type(JsonFieldType.STRING) 200 | .description("전화번호"), 201 | fieldWithPath("pageable.offset").ignored(), 202 | fieldWithPath("pageable.pageSize").ignored(), 203 | fieldWithPath("pageable.pageNumber").ignored(), 204 | fieldWithPath("pageable.paged").ignored(), 205 | fieldWithPath("pageable.unpaged").ignored(), 206 | fieldWithPath("pageable.sort.sorted").ignored(), 207 | fieldWithPath("pageable.sort.unsorted").ignored(), 208 | fieldWithPath("pageable.sort.empty").ignored(), 209 | fieldWithPath("sort.empty").ignored(), 210 | fieldWithPath("sort.sorted").ignored(), 211 | fieldWithPath("sort.unsorted").ignored(), 212 | fieldWithPath("totalPages").ignored(), 213 | fieldWithPath("size").ignored(), 214 | fieldWithPath("number").ignored(), 215 | fieldWithPath("first").ignored(), 216 | fieldWithPath("last").ignored(), 217 | fieldWithPath("numberOfElements").ignored(), 218 | fieldWithPath("empty").ignored(), 219 | fieldWithPath("totalElements").ignored() 220 | ) 221 | )); 222 | 223 | // then 224 | then(adminService).should().findUsers(any(), any()); 225 | } 226 | 227 | private Pageable getPageable() { 228 | return PageRequest.of(0, 10); 229 | } 230 | 231 | private List getUserListByName(String name) { 232 | return userResponseList.stream().filter(o -> o.getName().equals(name)) 233 | .collect(Collectors.toList()); 234 | } 235 | } 236 | -------------------------------------------------------------------------------- /src/test/java/com/flab/modu/admin/service/AdminServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.admin.service; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.mockito.ArgumentMatchers.any; 5 | import static org.mockito.BDDMockito.given; 6 | import static org.mockito.BDDMockito.then; 7 | 8 | import com.flab.modu.users.controller.UserDto.UserResponse; 9 | import com.flab.modu.users.domain.common.UserRole; 10 | import com.flab.modu.users.repository.UserRepository; 11 | import java.util.List; 12 | import java.util.stream.Collectors; 13 | import java.util.stream.IntStream; 14 | import org.junit.jupiter.api.DisplayName; 15 | import org.junit.jupiter.api.Test; 16 | import org.junit.jupiter.api.extension.ExtendWith; 17 | import org.mockito.InjectMocks; 18 | import org.mockito.Mock; 19 | import org.mockito.junit.jupiter.MockitoExtension; 20 | import org.springframework.data.domain.Page; 21 | import org.springframework.data.domain.PageImpl; 22 | import org.springframework.data.domain.PageRequest; 23 | import org.springframework.data.domain.Pageable; 24 | 25 | @DisplayName("Admin Service 테스트") 26 | @ExtendWith(MockitoExtension.class) 27 | class AdminServiceTest { 28 | 29 | @Mock 30 | private UserRepository userRepository; 31 | 32 | @InjectMocks 33 | private AdminService adminService; 34 | 35 | @Test 36 | @DisplayName("정상적으로 회원조회에 성공한다.") 37 | public void searchUsers_successful() throws Exception { 38 | // given 39 | List userResponseList = getUserResponseList(); 40 | long size = userResponseList.size(); 41 | Pageable pageable = PageRequest.of(0, 10); 42 | Page findUsers = new PageImpl<>(userResponseList, pageable, size); 43 | given(userRepository.searchByUsers(any(), any())).willReturn(findUsers); 44 | 45 | // when 46 | Page result = adminService.findUsers(any(), any()); 47 | 48 | // then 49 | assertThat(result.getTotalElements()).isEqualTo(size); 50 | assertThat(result.getTotalPages()).isEqualTo(1); 51 | then(userRepository).should().searchByUsers(any(), any()); 52 | } 53 | 54 | private List getUserResponseList() { 55 | return IntStream.range(0, 2) 56 | .mapToObj(i -> getUserResponse(i)) 57 | .collect(Collectors.toList()); 58 | } 59 | 60 | private UserResponse getUserResponse(int i) { 61 | return UserResponse.builder() 62 | .id((long) i) 63 | .email(getConcatData("test@modu.com", i)) 64 | .name(getConcatData("testmodu", i)) 65 | .phoneNumber(getConcatData("0100000000", i)) 66 | .role(UserRole.BUYER) 67 | .build(); 68 | } 69 | 70 | private String getConcatData(String data, int i) { 71 | return new StringBuilder(data).append(i).toString(); 72 | } 73 | } -------------------------------------------------------------------------------- /src/test/java/com/flab/modu/market/controller/MarketControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.market.controller; 2 | 3 | import static org.mockito.ArgumentMatchers.any; 4 | import static org.mockito.ArgumentMatchers.refEq; 5 | import static org.mockito.BDDMockito.given; 6 | import static org.mockito.BDDMockito.then; 7 | import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; 8 | import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; 9 | import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; 10 | import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; 11 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; 12 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 13 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; 14 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 15 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 16 | 17 | import com.fasterxml.jackson.databind.ObjectMapper; 18 | import com.flab.modu.market.controller.MarketDto.CreateResponse; 19 | import com.flab.modu.market.service.MarketService; 20 | import com.flab.modu.users.domain.common.UserConstant; 21 | import com.flab.modu.users.service.LoginService; 22 | import java.time.LocalDateTime; 23 | import org.apache.commons.lang3.RandomStringUtils; 24 | import org.assertj.core.api.Assertions; 25 | import org.hamcrest.CoreMatchers; 26 | import org.junit.jupiter.api.AfterEach; 27 | import org.junit.jupiter.api.BeforeEach; 28 | import org.junit.jupiter.api.DisplayName; 29 | import org.junit.jupiter.api.Test; 30 | import org.junit.jupiter.api.extension.ExtendWith; 31 | import org.junit.jupiter.params.ParameterizedTest; 32 | import org.junit.jupiter.params.provider.ValueSource; 33 | import org.springframework.beans.factory.annotation.Autowired; 34 | import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; 35 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 36 | import org.springframework.boot.test.mock.mockito.MockBean; 37 | import org.springframework.http.MediaType; 38 | import org.springframework.mock.web.MockHttpSession; 39 | import org.springframework.restdocs.payload.JsonFieldType; 40 | import org.springframework.test.context.junit.jupiter.SpringExtension; 41 | import org.springframework.test.web.servlet.MockMvc; 42 | import org.springframework.test.web.servlet.ResultActions; 43 | 44 | @DisplayName("Market Controller 테스트") 45 | @AutoConfigureRestDocs 46 | @ExtendWith({SpringExtension.class}) 47 | @WebMvcTest(MarketController.class) 48 | class MarketControllerTest { 49 | 50 | @Autowired 51 | private MockMvc mockMvc; 52 | 53 | private MockHttpSession session; 54 | 55 | @Autowired 56 | private ObjectMapper objectMapper; 57 | 58 | @MockBean 59 | private MarketService marketService; 60 | 61 | @MockBean 62 | private LoginService loginService; 63 | 64 | @BeforeEach 65 | public void setUp() throws Exception { 66 | String loginEmail = "user@test.com"; 67 | session = new MockHttpSession(); 68 | session.setAttribute(UserConstant.EMAIL, loginEmail); 69 | } 70 | 71 | @AfterEach 72 | public void clean() { 73 | session.clearAttributes(); 74 | } 75 | 76 | @Test 77 | @DisplayName("마켓 생성에 성공한다.") 78 | public void givenValidData_whenCreatingMarket_then200OK() throws Exception { 79 | //given 80 | MarketDto.CreateRequest createRequest = createMarketCreateRequest("MarketUrl", 81 | "Market Name"); 82 | MarketDto.CreateResponse createResponse = createMarketCreateResponse(createRequest); 83 | given(marketService.createMarket(any(MarketDto.CreateRequest.class), 84 | any(String.class))).willReturn( 85 | createResponse); 86 | 87 | //when 88 | ResultActions result = mockMvc.perform(post("/markets") 89 | .session(session) 90 | .content(objectMapper.writeValueAsString(createRequest)) 91 | .contentType(MediaType.APPLICATION_JSON) 92 | ); 93 | 94 | //then 95 | result.andDo(print()) 96 | .andExpect(status().isOk()) 97 | .andExpect(content().contentType(MediaType.APPLICATION_JSON)) 98 | .andExpect(jsonPath("$.name").value(CoreMatchers.equalTo(createRequest.getName()))) 99 | .andExpect(jsonPath("$.url").value(CoreMatchers.equalTo(createRequest.getUrl()))) 100 | .andExpect(jsonPath("$.sellerId").value( 101 | CoreMatchers.equalTo((String) session.getAttribute(UserConstant.EMAIL)))); 102 | then(marketService).should().createMarket(refEq(createRequest), 103 | refEq((String) session.getAttribute(UserConstant.EMAIL))); 104 | 105 | //document 106 | result.andDo(document("create-market", 107 | requestFields( 108 | fieldWithPath("name").type(JsonFieldType.STRING).description("마켓명"), 109 | fieldWithPath("url").type(JsonFieldType.STRING).description("마켓주소") 110 | ), 111 | responseFields( 112 | fieldWithPath("id").type(JsonFieldType.NUMBER).description("마켓아이디"), 113 | fieldWithPath("sellerId").type(JsonFieldType.STRING).description("판매자아이디"), 114 | fieldWithPath("name").type(JsonFieldType.STRING).description("마켓명"), 115 | fieldWithPath("url").type(JsonFieldType.STRING).description("마켓주소"), 116 | fieldWithPath("createdAt").type(JsonFieldType.STRING).description("생성일시"), 117 | fieldWithPath("modifiedAt").type(JsonFieldType.STRING).description("수정일시") 118 | ) 119 | )); 120 | } 121 | 122 | @Test 123 | @DisplayName("입력값 최대 길이로 마켓 생성에 성공한다.") 124 | public void givenMaximumLengthData_whenCreatingMarket_then200OK() throws Exception { 125 | //given 126 | String sellerId = RandomStringUtils.randomAlphabetic(50); 127 | String marketName = RandomStringUtils.random(200, "가나다라마바사아자차카타파하"); 128 | String url = RandomStringUtils.randomAlphabetic(100); 129 | 130 | Assertions.assertThat(sellerId.length()).isEqualTo(50); 131 | Assertions.assertThat(marketName.length()).isEqualTo(200); 132 | Assertions.assertThat(url.length()).isEqualTo(100); 133 | 134 | MarketDto.CreateRequest createRequest = createMarketCreateRequest(url, marketName); 135 | MarketDto.CreateResponse createResponse = createMarketCreateResponse(createRequest); 136 | given(marketService.createMarket(any(MarketDto.CreateRequest.class), 137 | any(String.class))).willReturn( 138 | createResponse); 139 | 140 | //when 141 | ResultActions result = mockMvc.perform(post("/markets") 142 | .session(session) 143 | .content(objectMapper.writeValueAsString(createRequest)) 144 | .contentType(MediaType.APPLICATION_JSON) 145 | ); 146 | 147 | //when 148 | result.andDo(print()) 149 | .andExpect(status().isOk()) 150 | .andExpect(content().contentType(MediaType.APPLICATION_JSON)) 151 | .andExpect(jsonPath("$.name").exists()) 152 | .andExpect(jsonPath("$.url").exists()) 153 | .andExpect(jsonPath("$.sellerId").exists()); 154 | then(marketService).should().createMarket(refEq(createRequest), 155 | refEq((String) session.getAttribute(UserConstant.EMAIL))); 156 | } 157 | 158 | @Test 159 | @DisplayName("입력값 길이 초과로 마켓 생성에 실패한다.") 160 | public void givenInvalidLengthData_whenCreatingMarket_then400BadRequestWithMessage() 161 | throws Exception { 162 | //given 163 | String sellerId = RandomStringUtils.randomAlphabetic(51); 164 | String marketName = RandomStringUtils.random(201, "가나다라마바사아자차카타파하"); 165 | String url = RandomStringUtils.randomAlphabetic(101); 166 | 167 | MarketDto.CreateRequest createMarketRequest = createMarketCreateRequest(url, marketName); 168 | 169 | //when 170 | ResultActions result = mockMvc.perform(post("/markets") 171 | .session(session) 172 | .content(objectMapper.writeValueAsString(createMarketRequest)) 173 | .contentType(MediaType.APPLICATION_JSON) 174 | ); 175 | 176 | //then 177 | result.andDo(print()) 178 | .andExpect(status().isBadRequest()) 179 | .andExpect(jsonPath("$.message").exists()); 180 | then(marketService).shouldHaveNoInteractions(); 181 | } 182 | 183 | @ParameterizedTest 184 | @ValueSource(strings = {"한글입력", "include blank", "url!!"}) 185 | @DisplayName("잘못된 형식의 URL로 마켓 생성 실패한다.") 186 | public void givenInvalidUrl_whenCreatingMarket_then400BadRequestWithMessage(String invalidUrl) 187 | throws Exception { 188 | //given 189 | MarketDto.CreateRequest createRequest = createMarketCreateRequest(invalidUrl, "마켓명"); 190 | 191 | //when 192 | ResultActions result = mockMvc.perform(post("/markets") 193 | .session(session) 194 | .content(objectMapper.writeValueAsString(createRequest)) 195 | .contentType(MediaType.APPLICATION_JSON) 196 | ); 197 | 198 | //then 199 | result.andDo(print()) 200 | .andExpect(status().isBadRequest()) 201 | .andExpect(jsonPath("$.message").exists()); 202 | then(marketService).shouldHaveNoInteractions(); 203 | } 204 | 205 | private MarketDto.CreateRequest createMarketCreateRequest(String url, String name) { 206 | return MarketDto.CreateRequest.builder() 207 | .name(name) 208 | .url(url) 209 | .build(); 210 | } 211 | 212 | private CreateResponse createMarketCreateResponse(MarketDto.CreateRequest createRequest) { 213 | MarketDto.CreateResponse createResponse = MarketDto.CreateResponse.builder() 214 | .market(createRequest.toEntity((String) session.getAttribute(UserConstant.EMAIL))) 215 | .build(); 216 | createResponse.setId(1L); 217 | createResponse.setCreatedAt(LocalDateTime.now()); 218 | createResponse.setModifiedAt(LocalDateTime.now()); 219 | return createResponse; 220 | } 221 | } -------------------------------------------------------------------------------- /src/test/java/com/flab/modu/market/repository/MarketRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.market.repository; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import com.flab.modu.global.config.JpaConfig; 6 | import com.flab.modu.market.domain.Market; 7 | import com.flab.modu.market.domain.MarketStatus; 8 | import java.util.List; 9 | import org.junit.jupiter.api.BeforeEach; 10 | import org.junit.jupiter.api.DisplayName; 11 | import org.junit.jupiter.api.Test; 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 14 | import org.springframework.context.annotation.Import; 15 | 16 | @DisplayName("Market JPA 연결 테스트") 17 | @Import(value = JpaConfig.class) 18 | @DataJpaTest 19 | public class MarketRepositoryTest { 20 | 21 | @Autowired 22 | private MarketRepository marketRepository; 23 | 24 | private Market insertedMarket; 25 | 26 | @BeforeEach 27 | private void beforeEach() { 28 | insertedMarket = insertMarketData("sellerId", "MarketUrl", "마켓명", MarketStatus.ACTIVE); 29 | } 30 | 31 | @Test 32 | @DisplayName("select 테스트") 33 | void givenTestData_whenSelecting_thenWorksFine() throws Exception { 34 | //given 35 | 36 | //when 37 | List markets = marketRepository.findAll(); 38 | 39 | //then 40 | assertThat(markets) 41 | .isNotNull() 42 | .hasSize(1); 43 | } 44 | 45 | @Test 46 | @DisplayName("insert 테스트") 47 | void givenTestData_whenInserting_thenWorksFine() throws Exception { 48 | //given 49 | long prevCount = marketRepository.count(); 50 | 51 | //when 52 | Market savedMarket = marketRepository.save( 53 | new Market("sellerId", "판매자명", "MarketUrl", MarketStatus.ACTIVE)); 54 | 55 | //then 56 | assertThat(marketRepository.count()).isEqualTo(prevCount + 1); 57 | } 58 | 59 | @Test 60 | @DisplayName("update 테스트") 61 | void givenTestData_whenUpdating_thenWorksFine() throws Exception { 62 | //given 63 | Market market = marketRepository.findById(insertedMarket.getId()).orElseThrow(); 64 | String updateUrl = "updatedUrl"; 65 | market.updateMarket(market.getName(), updateUrl, market.getStatus()); 66 | 67 | //when 68 | Market savedMarket = marketRepository.saveAndFlush(market); 69 | 70 | //then 71 | assertThat(savedMarket).hasFieldOrPropertyWithValue("url", updateUrl); 72 | } 73 | 74 | @Test 75 | @DisplayName("delete 테스트") 76 | void givenTestData_whenDeleting_thenWorksFine() throws Exception { 77 | //given 78 | Market market = marketRepository.findById(insertedMarket.getId()).orElseThrow(); 79 | long count = marketRepository.count(); 80 | 81 | // when 82 | marketRepository.delete(market); 83 | 84 | //then 85 | assertThat(marketRepository.count()).isEqualTo(count - 1); 86 | } 87 | 88 | private Market insertMarketData(String sellerId, String url, String name, MarketStatus status) { 89 | Market market = Market.builder() 90 | .sellerId(sellerId) 91 | .url(url) 92 | .name(name) 93 | .status(status) 94 | .build(); 95 | 96 | return marketRepository.save(market); 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/test/java/com/flab/modu/market/service/MarketServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.market.service; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertThrows; 4 | import static org.mockito.ArgumentMatchers.any; 5 | import static org.mockito.ArgumentMatchers.anyString; 6 | import static org.mockito.BDDMockito.given; 7 | import static org.mockito.BDDMockito.then; 8 | 9 | import com.flab.modu.market.controller.MarketDto; 10 | import com.flab.modu.market.controller.MarketDto.CreateRequest; 11 | import com.flab.modu.market.domain.Market; 12 | import com.flab.modu.market.exception.DuplicatedUrlException; 13 | import com.flab.modu.market.repository.MarketRepository; 14 | import org.junit.jupiter.api.DisplayName; 15 | import org.junit.jupiter.api.Test; 16 | import org.junit.jupiter.api.extension.ExtendWith; 17 | import org.mockito.InjectMocks; 18 | import org.mockito.Mock; 19 | import org.mockito.junit.jupiter.MockitoExtension; 20 | 21 | @DisplayName("Market Service 테스트") 22 | @ExtendWith(MockitoExtension.class) 23 | class MarketServiceTest { 24 | 25 | @Mock 26 | private MarketRepository marketRepository; 27 | 28 | @InjectMocks 29 | private MarketService marketService; 30 | 31 | @Test 32 | @DisplayName("정상적으로 마켓생성에 성공한다.") 33 | public void givenTestData_whenCreatingMarket_thenSuccess() { 34 | // given 35 | String sellerId = "sellerId"; 36 | MarketDto.CreateRequest createRequest = createMarketDto(); 37 | given(marketRepository.save(any(Market.class))).willReturn( 38 | createRequest.toEntity(sellerId)); 39 | 40 | // when 41 | marketService.createMarket(createRequest, sellerId); 42 | 43 | // then 44 | then(marketRepository).should().existsByUrl(anyString()); 45 | then(marketRepository).should().save(any(Market.class)); 46 | } 47 | 48 | @Test 49 | @DisplayName("마켓주소 중복으로 마켓생성에 실패한다.") 50 | public void givenDuplicatedUrl_whenCreatingMarket_thenFailure() { 51 | // given 52 | String sellerId = "sellerId"; 53 | MarketDto.CreateRequest createRequest = createMarketDto(); 54 | String existingUrl = "MarketUrl"; 55 | given(marketRepository.existsByUrl(existingUrl)).willReturn(true); 56 | 57 | // when 58 | assertThrows(DuplicatedUrlException.class, 59 | () -> marketService.createMarket(createRequest, sellerId)); 60 | 61 | // then 62 | then(marketRepository).should().existsByUrl(existingUrl); 63 | then(marketRepository).shouldHaveNoMoreInteractions(); 64 | } 65 | 66 | private CreateRequest createMarketDto() { 67 | return MarketDto.CreateRequest.builder() 68 | .url("MarketUrl") 69 | .name("마켓명") 70 | .build(); 71 | } 72 | } -------------------------------------------------------------------------------- /src/test/java/com/flab/modu/order/controller/OrderControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.order.controller; 2 | 3 | import static org.mockito.ArgumentMatchers.anyString; 4 | import static org.mockito.ArgumentMatchers.refEq; 5 | import static org.mockito.BDDMockito.given; 6 | import static org.mockito.BDDMockito.then; 7 | import static org.mockito.BDDMockito.willAnswer; 8 | import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; 9 | import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post; 10 | import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; 11 | import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; 12 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 13 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 14 | 15 | import com.fasterxml.jackson.databind.ObjectMapper; 16 | import com.flab.modu.order.controller.OrderDto.OrderRequest; 17 | import com.flab.modu.order.service.OrderCallService; 18 | import com.flab.modu.order.service.OrderService; 19 | import com.flab.modu.users.service.LoginService; 20 | import org.junit.jupiter.api.DisplayName; 21 | import org.junit.jupiter.api.Test; 22 | import org.junit.jupiter.api.extension.ExtendWith; 23 | import org.springframework.beans.factory.annotation.Autowired; 24 | import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; 25 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 26 | import org.springframework.boot.test.mock.mockito.MockBean; 27 | import org.springframework.http.MediaType; 28 | import org.springframework.restdocs.RestDocumentationExtension; 29 | import org.springframework.restdocs.payload.JsonFieldType; 30 | import org.springframework.test.web.servlet.MockMvc; 31 | 32 | @DisplayName("Order Controller 테스트") 33 | @ExtendWith(RestDocumentationExtension.class) 34 | @AutoConfigureRestDocs 35 | @WebMvcTest(OrderController.class) 36 | class OrderControllerTest { 37 | 38 | @MockBean 39 | private OrderCallService orderCallService; 40 | 41 | @MockBean 42 | private LoginService loginService; 43 | 44 | @Autowired 45 | private MockMvc mockMvc; 46 | 47 | @Autowired 48 | private ObjectMapper objectMapper; 49 | 50 | private final String USER_EMAIL = "test@modu.com"; 51 | 52 | @Test 53 | @DisplayName("상품주문 - 상품주문에 성공한다.") 54 | void createOrder_successful() throws Exception { 55 | OrderRequest orderRequest = createOrderRequest(1); 56 | 57 | willAnswer(invocation -> USER_EMAIL).given(loginService).getLoginUser(); 58 | given(orderCallService.callOrder(orderRequest, USER_EMAIL)).willReturn(1L); 59 | 60 | mockMvc.perform(post("/orders") 61 | .header("email", USER_EMAIL) 62 | .contentType(MediaType.APPLICATION_JSON) 63 | .content(objectMapper.writeValueAsString(orderRequest))) 64 | .andDo(print()) 65 | .andExpect(status().isCreated()) 66 | .andDo(document("orders/create/success", 67 | requestFields( 68 | fieldWithPath("productId").type(JsonFieldType.NUMBER) 69 | .description("구매할 상품의 ID"), 70 | fieldWithPath("amount").type(JsonFieldType.NUMBER) 71 | .description("주문수량"), 72 | fieldWithPath("deliveryMassage").type(JsonFieldType.STRING) 73 | .description("배송메시지") 74 | .optional(), 75 | fieldWithPath("receiverTel").type(JsonFieldType.STRING) 76 | .description("수령자 번호") 77 | .optional() 78 | ) 79 | )); 80 | 81 | then(orderCallService).should().callOrder(refEq(orderRequest), anyString()); 82 | } 83 | 84 | private OrderDto.OrderRequest createOrderRequest(int orderAmount) { 85 | return OrderDto.OrderRequest.builder() 86 | .productId(1L) 87 | .amount(orderAmount) 88 | .build(); 89 | } 90 | } -------------------------------------------------------------------------------- /src/test/java/com/flab/modu/order/service/OrderServiceConcurrencyTest.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.order.service; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertTrue; 5 | 6 | import com.flab.modu.global.config.JpaConfig; 7 | import com.flab.modu.market.domain.Market; 8 | import com.flab.modu.market.domain.MarketStatus; 9 | import com.flab.modu.market.repository.MarketRepository; 10 | import com.flab.modu.order.controller.OrderDto; 11 | import com.flab.modu.order.controller.OrderDto.OrderRequest; 12 | import com.flab.modu.order.exception.OrderFailureException; 13 | import com.flab.modu.order.repository.OrderRepository; 14 | import com.flab.modu.product.domain.common.ProductStatus; 15 | import com.flab.modu.product.domain.entity.Product; 16 | import com.flab.modu.product.repository.ProductRepository; 17 | import com.flab.modu.product.service.ProductService; 18 | import com.flab.modu.users.domain.common.UserRole; 19 | import com.flab.modu.users.domain.entity.User; 20 | import com.flab.modu.users.repository.UserRepository; 21 | import java.util.concurrent.ExecutionException; 22 | import java.util.concurrent.ExecutorService; 23 | import java.util.concurrent.Executors; 24 | import java.util.concurrent.Future; 25 | import org.junit.jupiter.api.BeforeEach; 26 | import org.junit.jupiter.api.DisplayName; 27 | import org.junit.jupiter.api.Test; 28 | import org.springframework.beans.factory.annotation.Autowired; 29 | import org.springframework.boot.test.context.SpringBootTest; 30 | import org.springframework.context.annotation.Import; 31 | 32 | @DisplayName("주문서비스 재고관리 테스트") 33 | @Import(value = JpaConfig.class) 34 | @SpringBootTest 35 | public class OrderServiceConcurrencyTest { 36 | 37 | @Autowired 38 | UserRepository userRepository; 39 | 40 | @Autowired 41 | OrderRepository orderRepository; 42 | 43 | @Autowired 44 | ProductRepository productRepository; 45 | 46 | @Autowired 47 | MarketRepository marketRepository; 48 | 49 | @Autowired 50 | ProductService productService; 51 | 52 | @Autowired 53 | OrderService orderService; 54 | 55 | @Autowired 56 | OrderCallService orderCallService; 57 | 58 | final String EMAIL = "test@test.com"; 59 | 60 | private Product savedProduct; 61 | 62 | @BeforeEach 63 | void setUp() { 64 | User user = User.builder() 65 | .email(EMAIL) 66 | .name("modu") 67 | .role(UserRole.BUYER) 68 | .password("test12345") 69 | .build(); 70 | 71 | userRepository.save(user); 72 | 73 | Market market = Market.builder() 74 | .sellerId("sellerId") 75 | .url("url") 76 | .name("name") 77 | .status(MarketStatus.ACTIVE) 78 | .build(); 79 | 80 | marketRepository.save(market); 81 | 82 | savedProduct = Product.builder().market(market) 83 | .stock(20) 84 | .image(new byte[]{}) 85 | .name("상품명") 86 | .status(ProductStatus.ACTIVE) 87 | .price(10000) 88 | .build(); 89 | 90 | productRepository.save(savedProduct); 91 | } 92 | 93 | @Test 94 | @DisplayName("낙관적 락 예외처리 테스트") 95 | void concurrency_transaction_rollback_test() throws Exception { 96 | // given 97 | int orderAmount = 1; 98 | OrderRequest orderRequest = createOrderRequest(orderAmount); 99 | ExecutorService executorService = Executors.newFixedThreadPool(3); 100 | 101 | // when 102 | Future future = executorService.submit( 103 | () -> { 104 | orderCallService.callOrder(orderRequest, EMAIL); 105 | }); 106 | Future future2 = executorService.submit( 107 | () -> { 108 | orderCallService.callOrder(orderRequest, EMAIL); 109 | }); 110 | Future future3 = executorService.submit( 111 | () -> { 112 | orderCallService.callOrder(orderRequest, EMAIL); 113 | }); 114 | 115 | Exception result = new Exception(); 116 | 117 | try { 118 | future.get(); 119 | future2.get(); 120 | future3.get(); 121 | } catch (ExecutionException e) { 122 | result = (Exception) e.getCause(); 123 | } 124 | 125 | // then 126 | assertTrue(result instanceof OrderFailureException); 127 | Product product = productService.getProduct(savedProduct.getId()); 128 | assertEquals(product.getStock(), savedProduct.getStock() - orderAmount); 129 | } 130 | 131 | private OrderDto.OrderRequest createOrderRequest(int orderAmount) { 132 | return OrderDto.OrderRequest.builder() 133 | .productId(savedProduct.getId()) 134 | .amount(orderAmount) 135 | .build(); 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /src/test/java/com/flab/modu/order/service/OrderServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.order.service; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | import static org.junit.jupiter.api.Assertions.assertThrows; 5 | import static org.mockito.ArgumentMatchers.any; 6 | import static org.mockito.ArgumentMatchers.anyInt; 7 | import static org.mockito.ArgumentMatchers.anyLong; 8 | import static org.mockito.ArgumentMatchers.anyString; 9 | import static org.mockito.ArgumentMatchers.eq; 10 | import static org.mockito.BDDMockito.given; 11 | import static org.mockito.BDDMockito.then; 12 | import static org.mockito.BDDMockito.willThrow; 13 | 14 | import com.flab.modu.market.domain.Market; 15 | import com.flab.modu.market.domain.MarketStatus; 16 | import com.flab.modu.order.controller.OrderDto; 17 | import com.flab.modu.order.domain.common.OrderStatus; 18 | import com.flab.modu.order.domain.entity.Order; 19 | import com.flab.modu.order.repository.OrderRepository; 20 | import com.flab.modu.product.domain.common.ProductStatus; 21 | import com.flab.modu.product.domain.entity.Product; 22 | import com.flab.modu.product.exception.InsufficientStockException; 23 | import com.flab.modu.product.exception.NotExistProductException; 24 | import com.flab.modu.product.service.ProductService; 25 | import com.flab.modu.users.domain.common.UserRole; 26 | import com.flab.modu.users.domain.entity.User; 27 | import com.flab.modu.users.exception.NotExistedUserException; 28 | import com.flab.modu.users.repository.UserRepository; 29 | import java.util.Optional; 30 | import org.junit.jupiter.api.BeforeEach; 31 | import org.junit.jupiter.api.DisplayName; 32 | import org.junit.jupiter.api.Test; 33 | import org.junit.jupiter.api.extension.ExtendWith; 34 | import org.mockito.InjectMocks; 35 | import org.mockito.Mock; 36 | import org.mockito.junit.jupiter.MockitoExtension; 37 | 38 | @ExtendWith(MockitoExtension.class) 39 | class OrderServiceTest { 40 | 41 | @Mock 42 | private UserRepository userRepository; 43 | 44 | @Mock 45 | private OrderRepository orderRepository; 46 | 47 | @Mock 48 | private ProductService productService; 49 | 50 | @InjectMocks 51 | private OrderService orderService; 52 | 53 | @Test 54 | @DisplayName("정상적으로 주문 생성에 성공한다.") 55 | public void createOrder_successful() throws Exception { 56 | // give 57 | OrderDto.OrderRequest orderRequest = createOrderRequest(1); 58 | Product product = createProduct(10); 59 | User buyer = createBuyer(); 60 | Order order = createOrder(buyer); 61 | given(userRepository.findByEmail(anyString())).willReturn(Optional.of(buyer)); 62 | given(productService.getProduct(anyLong())).willReturn(product); 63 | given(orderRepository.save(any(Order.class))).willReturn(order); 64 | 65 | // when 66 | Long orderId = orderService.createOrder(orderRequest, buyer.getEmail()); 67 | 68 | // then 69 | then(userRepository).should().findByEmail(anyString()); 70 | then(productService).should().getProduct(anyLong()); 71 | then(orderRepository).should().save(any(Order.class)); 72 | } 73 | 74 | @Test 75 | @DisplayName("존재하지 않는 유저의 주문은 실패한다.") 76 | public void notExistEmail_createOrder_failure() throws Exception { 77 | // give 78 | OrderDto.OrderRequest orderRequest = createOrderRequest(1); 79 | given(userRepository.findByEmail(anyString())).willThrow(new NotExistedUserException()); 80 | 81 | // when 82 | assertThrows(NotExistedUserException.class, 83 | () -> orderService.createOrder(orderRequest, "noExistUserEmail")); 84 | 85 | // then 86 | then(userRepository).should().findByEmail(anyString()); 87 | then(userRepository).shouldHaveNoMoreInteractions(); 88 | then(productService).shouldHaveNoInteractions(); 89 | then(orderRepository).shouldHaveNoInteractions(); 90 | } 91 | 92 | @Test 93 | @DisplayName("존재하지 않는 상품의 주문은 실패한다.") 94 | public void notExistProduct_createOrder_failure() throws Exception { 95 | // give 96 | OrderDto.OrderRequest orderRequest = createOrderRequest(1); 97 | User buyer = createBuyer(); 98 | given(userRepository.findByEmail(anyString())).willReturn(Optional.of(buyer)); 99 | given(productService.getProduct(anyLong())).willThrow( 100 | new NotExistProductException()); 101 | 102 | // when 103 | assertThrows(NotExistProductException.class, 104 | () -> orderService.createOrder(orderRequest, buyer.getEmail())); 105 | 106 | // then 107 | then(userRepository).should().findByEmail(anyString()); 108 | then(productService).should().getProduct(anyLong()); 109 | then(userRepository).shouldHaveNoMoreInteractions(); 110 | then(orderRepository).shouldHaveNoInteractions(); 111 | } 112 | 113 | @Test 114 | @DisplayName("상품재고가 다 떨어졌다면 상품의 주문은 실패한다.") 115 | public void zeroStockProduct_createOrder_failure() throws Exception { 116 | // give 117 | OrderDto.OrderRequest orderRequest = createOrderRequest(10); 118 | Product product = createProduct(0); 119 | User buyer = createBuyer(); 120 | given(userRepository.findByEmail(anyString())).willReturn(Optional.of(buyer)); 121 | given(productService.getProduct(anyLong())).willReturn(product); 122 | willThrow(new InsufficientStockException("상품의 재고가 부족합니다.")).given(productService) 123 | .sellProduct(eq(product), anyInt()); 124 | 125 | // when 126 | Throwable exception = assertThrows( 127 | InsufficientStockException.class, 128 | () -> orderService.createOrder(orderRequest, buyer.getEmail())); 129 | assertEquals("상품의 재고가 부족합니다.", exception.getMessage()); 130 | 131 | // then 132 | then(userRepository).should().findByEmail(anyString()); 133 | then(productService).should().getProduct(anyLong()); 134 | then(productService).should().sellProduct(eq(product), anyInt()); 135 | then(orderRepository).shouldHaveNoInteractions(); 136 | } 137 | 138 | @Test 139 | @DisplayName("주문수량보다 상품재고가 부족하면 상품의 주문은 실패한다.") 140 | public void insufficientStock_createOrder_failure() throws Exception { 141 | // give 142 | OrderDto.OrderRequest orderRequest = createOrderRequest(10); 143 | Product product = createProduct(2); 144 | User buyer = createBuyer(); 145 | given(userRepository.findByEmail(anyString())).willReturn(Optional.of(buyer)); 146 | given(productService.getProduct(anyLong())).willReturn(product); 147 | willThrow(new InsufficientStockException("주문 수량이 상품의 재고보다 많습니다.")).given(productService) 148 | .sellProduct(eq(product), anyInt()); 149 | 150 | // when 151 | Throwable exception = assertThrows( 152 | InsufficientStockException.class, 153 | () -> orderService.createOrder(orderRequest, buyer.getEmail())); 154 | assertEquals("주문 수량이 상품의 재고보다 많습니다.", exception.getMessage()); 155 | 156 | // then 157 | then(userRepository).should().findByEmail(anyString()); 158 | then(productService).should().getProduct(anyLong()); 159 | then(productService).should().sellProduct(eq(product), anyInt()); 160 | then(orderRepository).shouldHaveNoInteractions(); 161 | } 162 | 163 | 164 | private OrderDto.OrderRequest createOrderRequest(int orderAmount) { 165 | return OrderDto.OrderRequest.builder() 166 | .productId(1L) 167 | .amount(orderAmount) 168 | .build(); 169 | } 170 | 171 | private User createBuyer() { 172 | return User.builder() 173 | .email("test@modu.com") 174 | .name("테스트네임") 175 | .password("test12345@") 176 | .role(UserRole.BUYER) 177 | .phoneNumber("01012345678") 178 | .build(); 179 | } 180 | 181 | private Product createProduct(int stock) { 182 | return Product.builder() 183 | .name("테스트상품") 184 | .stock(stock) 185 | .status(ProductStatus.ACTIVE) 186 | .market(createMarket()) 187 | .build(); 188 | } 189 | 190 | private Market createMarket() { 191 | return Market.builder() 192 | .name("테스트마켓") 193 | .url("testUrl") 194 | .sellerId("testId") 195 | .status(MarketStatus.ACTIVE) 196 | .build(); 197 | } 198 | 199 | private Order createOrder(User buyer) { 200 | return Order.builder() 201 | .buyer(buyer) 202 | .status(OrderStatus.PAYMENT_CONFIRMED) 203 | .build(); 204 | } 205 | } -------------------------------------------------------------------------------- /src/test/java/com/flab/modu/product/controller/ProductControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.product.controller; 2 | 3 | import static org.mockito.ArgumentMatchers.any; 4 | import static org.mockito.ArgumentMatchers.nullable; 5 | import static org.mockito.ArgumentMatchers.refEq; 6 | import static org.mockito.BDDMockito.given; 7 | import static org.mockito.BDDMockito.then; 8 | import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; 9 | import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; 10 | import static org.springframework.restdocs.payload.PayloadDocumentation.requestPartFields; 11 | import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; 12 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; 13 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 14 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; 15 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 16 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 17 | 18 | import com.fasterxml.jackson.databind.ObjectMapper; 19 | import com.flab.modu.market.domain.Market; 20 | import com.flab.modu.market.exception.MarketNoPermissionException; 21 | import com.flab.modu.market.exception.MarketNotFoundException; 22 | import com.flab.modu.product.domain.common.ProductStatus; 23 | import com.flab.modu.product.domain.entity.Product; 24 | import com.flab.modu.product.exception.WrongImageDataException; 25 | import com.flab.modu.product.service.ProductService; 26 | import com.flab.modu.users.domain.common.UserConstant; 27 | import com.flab.modu.users.service.LoginService; 28 | import java.io.IOException; 29 | import org.hamcrest.CoreMatchers; 30 | import org.junit.jupiter.api.AfterEach; 31 | import org.junit.jupiter.api.BeforeEach; 32 | import org.junit.jupiter.api.DisplayName; 33 | import org.junit.jupiter.api.Test; 34 | import org.junit.jupiter.api.extension.ExtendWith; 35 | import org.springframework.beans.factory.annotation.Autowired; 36 | import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; 37 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 38 | import org.springframework.boot.test.mock.mockito.MockBean; 39 | import org.springframework.http.MediaType; 40 | import org.springframework.mock.web.MockHttpSession; 41 | import org.springframework.mock.web.MockMultipartFile; 42 | import org.springframework.restdocs.payload.JsonFieldType; 43 | import org.springframework.test.context.junit.jupiter.SpringExtension; 44 | import org.springframework.test.web.servlet.MockMvc; 45 | import org.springframework.test.web.servlet.ResultActions; 46 | import org.springframework.web.multipart.MultipartFile; 47 | 48 | @DisplayName("Product Controller 테스트") 49 | @AutoConfigureRestDocs 50 | @ExtendWith({SpringExtension.class}) 51 | @WebMvcTest(ProductController.class) 52 | class ProductControllerTest { 53 | 54 | @Autowired 55 | private MockMvc mockMvc; 56 | 57 | private MockHttpSession session; 58 | 59 | @Autowired 60 | private ObjectMapper objectMapper; 61 | 62 | @MockBean 63 | private ProductService productService; 64 | 65 | @MockBean 66 | private LoginService loginService; 67 | 68 | private final Market preparedMarket = Market.builder().sellerId("testUser").build(); 69 | 70 | @BeforeEach 71 | public void setUp() throws Exception { 72 | String loginEmail = "user@test.com"; 73 | session = new MockHttpSession(); 74 | session.setAttribute(UserConstant.EMAIL, loginEmail); 75 | } 76 | 77 | @AfterEach 78 | public void clean() { 79 | session.clearAttributes(); 80 | } 81 | 82 | @Test 83 | @DisplayName("상품 생성에 성공한다.") 84 | public void givenValidData_whenCreatingProduct_then200OK() throws Exception { 85 | //given 86 | MockMultipartFile multipartFile = createMultipartFile(); 87 | ProductDto.CreateRequest createRequest = createProductCreateRequest(1L, "상품1", 10000, 20, 88 | ProductStatus.ACTIVE); 89 | ProductDto.CreateResponse createResponse = createProductCreateResponse(createRequest, 90 | getImageByteArr(multipartFile)); 91 | given(productService.createProduct(any(ProductDto.CreateRequest.class), 92 | any(MultipartFile.class), any(String.class))) 93 | .willReturn(createResponse); 94 | 95 | //when 96 | ResultActions result = mockMvc.perform(multipart("/products") 97 | .file(multipartFile) 98 | .file(new MockMultipartFile("product", "product", MediaType.APPLICATION_JSON_VALUE, 99 | objectMapper.writeValueAsBytes(createRequest))) 100 | .session(session) 101 | .accept(MediaType.APPLICATION_JSON) 102 | ); 103 | 104 | //then 105 | result.andDo(print()) 106 | .andExpect(status().isOk()) 107 | .andExpect(content().contentType(MediaType.APPLICATION_JSON)) 108 | .andExpect(jsonPath("$.name").value(CoreMatchers.equalTo(createRequest.getName()))) 109 | .andExpect(jsonPath("$.price").value(CoreMatchers.equalTo(createRequest.getPrice()))) 110 | .andExpect(jsonPath("$.status").value( 111 | CoreMatchers.equalTo(createRequest.getStatus().getCode()))) 112 | .andExpect(jsonPath("$.stock").value(CoreMatchers.equalTo(createRequest.getStock()))) 113 | .andExpect(jsonPath("$.market").value(CoreMatchers.notNullValue())); 114 | 115 | then(productService).should().createProduct(refEq(createRequest), 116 | refEq(multipartFile), 117 | refEq((String) session.getAttribute(UserConstant.EMAIL))); 118 | 119 | //document 120 | result.andDo(document("create-product", 121 | requestPartFields("product", 122 | fieldWithPath("marketId").type(JsonFieldType.NUMBER).description("마켓고유아이디"), 123 | fieldWithPath("name").type(JsonFieldType.STRING).description("상품명"), 124 | fieldWithPath("price").type(JsonFieldType.NUMBER).description("상품가격"), 125 | fieldWithPath("stock").type(JsonFieldType.NUMBER).description("재고"), 126 | fieldWithPath("status").type(JsonFieldType.STRING) 127 | .description("상태(활성:ACTIVE/비활성:DISABLE)") 128 | ), 129 | responseFields( 130 | fieldWithPath("id").optional().type(JsonFieldType.NUMBER).description("상품아이디"), 131 | fieldWithPath("market.id").optional().type(JsonFieldType.NUMBER) 132 | .description("마켓아이디"), 133 | fieldWithPath("market.name").optional().type(JsonFieldType.STRING) 134 | .description("마켓명"), 135 | fieldWithPath("market.sellerId").optional().type(JsonFieldType.STRING) 136 | .description("판매자아이디"), 137 | fieldWithPath("market.status").optional().type(JsonFieldType.STRING) 138 | .description("마켓상태"), 139 | fieldWithPath("market.url").optional().type(JsonFieldType.STRING) 140 | .description("마켓주소"), 141 | fieldWithPath("market.createdAt").optional().type(JsonFieldType.STRING) 142 | .description("마켓생성날짜"), 143 | fieldWithPath("market.modifiedAt").optional().type(JsonFieldType.STRING) 144 | .description("마켓수정날짜"), 145 | fieldWithPath("name").type(JsonFieldType.STRING).description("상품명"), 146 | fieldWithPath("price").type(JsonFieldType.NUMBER).description("가격"), 147 | fieldWithPath("stock").type(JsonFieldType.NUMBER).description("재고"), 148 | fieldWithPath("status").type(JsonFieldType.STRING) 149 | .description("상태(활성:ACTIVE/비활성:DISABLE)"), 150 | fieldWithPath("image").type(JsonFieldType.STRING).description("이미지바이너리") 151 | ) 152 | )); 153 | } 154 | 155 | @Test 156 | @DisplayName("이미지 정보가 없어도 상품 생성에 성공한다.") 157 | public void givenNoImage_whenCreatingProduct_then200OK() throws Exception { 158 | //given 159 | ProductDto.CreateRequest createRequest = createProductCreateRequest(1L, "상품1", 10000, 20, 160 | ProductStatus.ACTIVE); 161 | ProductDto.CreateResponse createResponse = createProductCreateResponse(createRequest, 162 | null); 163 | given(productService.createProduct(any(ProductDto.CreateRequest.class), 164 | nullable(MultipartFile.class), any(String.class))) 165 | .willReturn(createResponse); 166 | 167 | //when 168 | ResultActions result = mockMvc.perform(multipart("/products") 169 | .file(new MockMultipartFile("product", "product", MediaType.APPLICATION_JSON_VALUE, 170 | objectMapper.writeValueAsBytes(createRequest))) 171 | .session(session) 172 | .accept(MediaType.APPLICATION_JSON) 173 | ); 174 | 175 | //then 176 | result.andDo(print()) 177 | .andExpect(status().isOk()) 178 | .andExpect(content().contentType(MediaType.APPLICATION_JSON)) 179 | .andExpect(jsonPath("$.name").value(CoreMatchers.equalTo(createRequest.getName()))) 180 | .andExpect(jsonPath("$.price").value(CoreMatchers.equalTo(createRequest.getPrice()))) 181 | .andExpect(jsonPath("$.status").value( 182 | CoreMatchers.equalTo(createRequest.getStatus().getCode()))) 183 | .andExpect(jsonPath("$.stock").value(CoreMatchers.equalTo(createRequest.getStock()))) 184 | .andExpect(jsonPath("$.market").value(CoreMatchers.notNullValue())); 185 | 186 | then(productService).should().createProduct(refEq(createRequest), 187 | refEq(null), 188 | refEq((String) session.getAttribute(UserConstant.EMAIL))); 189 | } 190 | 191 | @Test 192 | @DisplayName("필수 파라메터 marketId 누락으로 상품 생성에 실패한다.") 193 | public void givenNoMarketIdParameter_whenCreatingProduct_then400BadRequest() throws Exception { 194 | //given 195 | ProductDto.CreateRequest createRequest = createProductCreateRequest(null, "상품1", 10000, 20, 196 | ProductStatus.ACTIVE); 197 | 198 | //when 199 | ResultActions result = mockMvc.perform(multipart("/products") 200 | .file(new MockMultipartFile("product", "product", MediaType.APPLICATION_JSON_VALUE, 201 | objectMapper.writeValueAsBytes(createRequest))) 202 | .session(session) 203 | .accept(MediaType.APPLICATION_JSON) 204 | ); 205 | 206 | //then 207 | result.andDo(print()) 208 | .andExpect(status().isBadRequest()) 209 | .andExpect(content().contentType(MediaType.APPLICATION_JSON)) 210 | .andExpect(jsonPath("$.message").value(CoreMatchers.notNullValue())); 211 | 212 | then(productService).shouldHaveNoInteractions(); 213 | } 214 | 215 | @Test 216 | @DisplayName("market 소유 권한 문제로 상품 생성에 실패한다.") 217 | public void givenMarketNoPermission_whenCreatingProduct_then400BadRequest() throws Exception { 218 | //given 219 | ProductDto.CreateRequest createRequest = createProductCreateRequest(1L, "상품1", 10000, 20, 220 | ProductStatus.ACTIVE); 221 | given(productService.createProduct(any(ProductDto.CreateRequest.class), 222 | nullable(MultipartFile.class), any(String.class))) 223 | .willThrow(new MarketNoPermissionException()); 224 | 225 | //when 226 | ResultActions result = mockMvc.perform(multipart("/products") 227 | .file(new MockMultipartFile("product", "product", MediaType.APPLICATION_JSON_VALUE, 228 | objectMapper.writeValueAsBytes(createRequest))) 229 | .session(session) 230 | ); 231 | 232 | //then 233 | result.andDo(print()) 234 | .andExpect(status().isBadRequest()); 235 | 236 | then(productService).should().createProduct(refEq(createRequest), 237 | refEq(null), 238 | refEq((String) session.getAttribute(UserConstant.EMAIL))); 239 | 240 | then(productService).shouldHaveNoMoreInteractions(); 241 | } 242 | 243 | @Test 244 | @DisplayName("존재하지않는 market정보로 상품 생성에 실패한다.") 245 | public void givenMarketNotFound_whenCreatingProduct_then400BadRequest() throws Exception { 246 | //given 247 | ProductDto.CreateRequest createRequest = createProductCreateRequest(1L, "상품1", 10000, 20, 248 | ProductStatus.ACTIVE); 249 | given(productService.createProduct(any(ProductDto.CreateRequest.class), 250 | nullable(MultipartFile.class), any(String.class))) 251 | .willThrow(new MarketNotFoundException()); 252 | 253 | //when 254 | ResultActions result = mockMvc.perform(multipart("/products") 255 | .file(new MockMultipartFile("product", "product", MediaType.APPLICATION_JSON_VALUE, 256 | objectMapper.writeValueAsBytes(createRequest))) 257 | .session(session) 258 | ); 259 | 260 | //then 261 | result.andDo(print()) 262 | .andExpect(status().isBadRequest()); 263 | 264 | then(productService).should().createProduct(refEq(createRequest), 265 | refEq(null), 266 | refEq((String) session.getAttribute(UserConstant.EMAIL))); 267 | 268 | then(productService).shouldHaveNoMoreInteractions(); 269 | } 270 | 271 | @Test 272 | @DisplayName("잘못된 이미지바이너리 정보로 상품 생성에 실패한다.") 273 | public void givenWrongImageData_whenCreatingProduct_then400BadRequest() throws Exception { 274 | //given 275 | ProductDto.CreateRequest createRequest = createProductCreateRequest(1L, "상품1", 10000, 20, 276 | ProductStatus.ACTIVE); 277 | given(productService.createProduct(any(ProductDto.CreateRequest.class), 278 | nullable(MultipartFile.class), any(String.class))) 279 | .willThrow(new WrongImageDataException()); 280 | 281 | //when 282 | ResultActions result = mockMvc.perform(multipart("/products") 283 | .file(new MockMultipartFile("product", "product", MediaType.APPLICATION_JSON_VALUE, 284 | objectMapper.writeValueAsBytes(createRequest))) 285 | .session(session) 286 | ); 287 | 288 | //then 289 | result.andDo(print()) 290 | .andExpect(status().isBadRequest()); 291 | 292 | then(productService).should().createProduct(refEq(createRequest), 293 | refEq(null), 294 | refEq((String) session.getAttribute(UserConstant.EMAIL))); 295 | 296 | then(productService).shouldHaveNoMoreInteractions(); 297 | } 298 | 299 | private ProductDto.CreateRequest createProductCreateRequest(Long marketId, String name, 300 | Integer price, Integer stock, ProductStatus status) { 301 | return ProductDto.CreateRequest.builder() 302 | .marketId(marketId) 303 | .price(price) 304 | .name(name) 305 | .stock(stock) 306 | .status(status) 307 | .build(); 308 | } 309 | 310 | private ProductDto.CreateResponse createProductCreateResponse( 311 | ProductDto.CreateRequest createRequest, byte[] image) { 312 | Product product = createRequest.toEntity(preparedMarket, image); 313 | return ProductDto.CreateResponse.builder().product(product).build(); 314 | } 315 | 316 | private MockMultipartFile createMultipartFile() { 317 | return new MockMultipartFile("image", "이미지.png", "image/png", "".getBytes()); 318 | } 319 | 320 | private byte[] getImageByteArr(MultipartFile multipartFile) { 321 | try { 322 | return multipartFile.getBytes(); 323 | } catch (IOException e) { 324 | return new byte[]{}; 325 | } 326 | } 327 | } -------------------------------------------------------------------------------- /src/test/java/com/flab/modu/product/repository/ProductRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.product.repository; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import com.flab.modu.global.config.JpaConfig; 6 | import com.flab.modu.market.domain.Market; 7 | import com.flab.modu.market.domain.MarketStatus; 8 | import com.flab.modu.market.repository.MarketRepository; 9 | import com.flab.modu.product.domain.common.ProductStatus; 10 | import com.flab.modu.product.domain.entity.Product; 11 | import java.util.List; 12 | import org.junit.jupiter.api.BeforeEach; 13 | import org.junit.jupiter.api.DisplayName; 14 | import org.junit.jupiter.api.Test; 15 | import org.springframework.beans.factory.annotation.Autowired; 16 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 17 | import org.springframework.context.annotation.Import; 18 | 19 | @DisplayName("Product JPA 연결 테스트") 20 | @Import(value = JpaConfig.class) 21 | @DataJpaTest 22 | public class ProductRepositoryTest { 23 | 24 | @Autowired 25 | private MarketRepository marketRepository; 26 | 27 | @Autowired 28 | private ProductRepository productRepository; 29 | 30 | private Market savedMarket; 31 | 32 | private Product savedProduct; 33 | 34 | @BeforeEach 35 | private void beforeEach() { 36 | Market market = Market.builder() 37 | .sellerId("sellerId") 38 | .url("url") 39 | .name("name") 40 | .status(MarketStatus.ACTIVE) 41 | .build(); 42 | 43 | savedMarket = marketRepository.save(market); 44 | 45 | savedProduct = insertProductData(savedMarket, 20, "상품명",10000,ProductStatus.ACTIVE,new byte[]{}); 46 | } 47 | 48 | @Test 49 | @DisplayName("select 테스트") 50 | void givenTestData_whenSelecting_thenWorksFine() throws Exception { 51 | //given 52 | 53 | //when 54 | List products = productRepository.findAll(); 55 | 56 | //then 57 | assertThat(products) 58 | .isNotNull() 59 | .hasSize(1); 60 | } 61 | 62 | @Test 63 | @DisplayName("insert 테스트") 64 | void givenTestData_whenInserting_thenWorksFine() throws Exception { 65 | //given 66 | long prevCount = productRepository.count(); 67 | 68 | //when 69 | productRepository.save( 70 | new Product(savedMarket,"상품명2",1, 150000, new byte[]{}, ProductStatus.ACTIVE) 71 | ); 72 | 73 | //then 74 | assertThat(productRepository.count()).isEqualTo(prevCount + 1); 75 | } 76 | 77 | @Test 78 | @DisplayName("update 테스트") 79 | void givenTestData_whenUpdating_thenWorksFine() throws Exception { 80 | //given 81 | Product product = productRepository.findById(savedProduct.getId()).orElseThrow(); 82 | Integer updatePrice = 1000; 83 | product.update(product.getName(), product.getStock(), updatePrice ,product.getImage(),product.getStatus()); 84 | 85 | //when 86 | Product updatedProduct = productRepository.saveAndFlush(product); 87 | 88 | //then 89 | assertThat(updatedProduct).hasFieldOrPropertyWithValue("price", updatePrice); 90 | } 91 | 92 | @Test 93 | @DisplayName("delete 테스트") 94 | void givenTestData_whenDeleting_thenWorksFine() throws Exception { 95 | //given 96 | Product product = productRepository.findById(savedProduct.getId()).orElseThrow(); 97 | long count = productRepository.count(); 98 | 99 | // when 100 | productRepository.delete(product); 101 | 102 | //then 103 | assertThat(productRepository.count()).isEqualTo(count - 1); 104 | } 105 | 106 | private Product insertProductData(Market market, Integer stock, String name, Integer price, ProductStatus status, byte[] image) { 107 | Product product = Product.builder().market(market) 108 | .stock(stock) 109 | .image(image) 110 | .name(name) 111 | .status(status) 112 | .price(price) 113 | .build(); 114 | 115 | return productRepository.save(product); 116 | } 117 | 118 | } 119 | -------------------------------------------------------------------------------- /src/test/java/com/flab/modu/product/service/ProductServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.product.service; 2 | 3 | import static org.mockito.ArgumentMatchers.any; 4 | import static org.mockito.BDDMockito.given; 5 | import static org.mockito.BDDMockito.then; 6 | 7 | import com.flab.modu.market.domain.Market; 8 | import com.flab.modu.market.exception.MarketNoPermissionException; 9 | import com.flab.modu.market.exception.MarketNotFoundException; 10 | import com.flab.modu.market.repository.MarketRepository; 11 | import com.flab.modu.product.controller.ProductDto; 12 | import com.flab.modu.product.domain.common.ProductStatus; 13 | import com.flab.modu.product.domain.entity.Product; 14 | import com.flab.modu.product.repository.ProductRepository; 15 | import java.util.Optional; 16 | import org.junit.jupiter.api.Assertions; 17 | import org.junit.jupiter.api.DisplayName; 18 | import org.junit.jupiter.api.Test; 19 | import org.junit.jupiter.api.extension.ExtendWith; 20 | import org.mockito.InjectMocks; 21 | import org.mockito.Mock; 22 | import org.mockito.junit.jupiter.MockitoExtension; 23 | 24 | @DisplayName("Product Service 테스트") 25 | @ExtendWith(MockitoExtension.class) 26 | public class ProductServiceTest { 27 | 28 | @Mock 29 | private ProductRepository productRepository; 30 | 31 | @Mock 32 | private MarketRepository marketRepository; 33 | 34 | @InjectMocks 35 | private ProductService productService; 36 | 37 | @Test 38 | @DisplayName("정상적으로 마켓생성에 성공한다.") 39 | public void givenTestData_whenCreatingMarket_thenSuccess() { 40 | // given 41 | String sellerId = "sellerId"; 42 | ProductDto.CreateRequest createRequest = createProductDto(1L, "상품명", 25000, 100, 43 | ProductStatus.ACTIVE); 44 | Market market = Market.builder().sellerId(sellerId).build(); 45 | 46 | given(marketRepository.findById(any(Long.class))).willReturn( 47 | Optional.of(market)); 48 | given(productRepository.save(any(Product.class))).willReturn( 49 | createRequest.toEntity(market, null)); 50 | 51 | // when 52 | productService.createProduct(createRequest, null, sellerId); 53 | 54 | // then 55 | then(marketRepository).should().findById(any(Long.class)); 56 | then(productRepository).should().save(any(Product.class)); 57 | } 58 | 59 | @Test 60 | @DisplayName("존재하지 않는 마켓정보로 상품 생성에 실패한다.") 61 | public void givenNotExistMarketId_whenCreatingProduct_thenThrowMarketNotFoundException() { 62 | // given 63 | String sellerId = "sellerId"; 64 | ProductDto.CreateRequest createRequest = createProductDto(1234L, "상품명", 25000, 100, 65 | ProductStatus.ACTIVE); 66 | Market market = Market.builder().sellerId(sellerId).build(); 67 | 68 | given(marketRepository.findById(any(Long.class))).willReturn( 69 | Optional.empty()); 70 | 71 | // when 72 | Assertions.assertThrows(MarketNotFoundException.class, 73 | () -> productService.createProduct(createRequest, null, sellerId)); 74 | 75 | // then 76 | then(marketRepository).should().findById(any(Long.class)); 77 | then(marketRepository).shouldHaveNoMoreInteractions(); 78 | then(productRepository).shouldHaveNoInteractions(); 79 | } 80 | 81 | @Test 82 | @DisplayName("내 소유가 아닌 마켓정보로 상품 생성에 실패한다.") 83 | public void givenNotMineMarket_whenCreatingProduct_thenThrowMarketNoPermissionException() 84 | throws Exception { 85 | // given 86 | String sellerId = "sellerId"; 87 | String anotherSellerId = "hello"; 88 | ProductDto.CreateRequest createRequest = createProductDto(1234L, "상품명", 25000, 100, 89 | ProductStatus.ACTIVE); 90 | Market market = Market.builder().sellerId(sellerId).build(); 91 | 92 | given(marketRepository.findById(any(Long.class))).willReturn( 93 | Optional.of(market)); 94 | 95 | // when 96 | Assertions.assertThrows(MarketNoPermissionException.class, 97 | () -> productService.createProduct(createRequest, null, anotherSellerId)); 98 | 99 | // then 100 | then(marketRepository).should().findById(any(Long.class)); 101 | then(marketRepository).shouldHaveNoMoreInteractions(); 102 | then(productRepository).shouldHaveNoInteractions(); 103 | } 104 | 105 | private ProductDto.CreateRequest createProductDto(Long marketId, String name, Integer price, 106 | Integer stock, ProductStatus status) { 107 | return ProductDto.CreateRequest.builder() 108 | .marketId(marketId) 109 | .price(price) 110 | .name(name) 111 | .stock(stock) 112 | .status(status) 113 | .build(); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /src/test/java/com/flab/modu/users/controller/UserControllerTest.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.users.controller; 2 | 3 | import static org.mockito.ArgumentMatchers.any; 4 | import static org.mockito.ArgumentMatchers.refEq; 5 | import static org.mockito.BDDMockito.then; 6 | import static org.mockito.BDDMockito.willAnswer; 7 | import static org.mockito.BDDMockito.willDoNothing; 8 | import static org.mockito.BDDMockito.willThrow; 9 | import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; 10 | import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post; 11 | import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; 12 | import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; 13 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; 14 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 15 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 16 | 17 | import com.fasterxml.jackson.databind.ObjectMapper; 18 | import com.flab.modu.users.controller.UserDto.CreateRequest; 19 | import com.flab.modu.users.controller.UserDto.LoginRequest; 20 | import com.flab.modu.users.controller.UserDto.PasswordRequest; 21 | import com.flab.modu.users.exception.DuplicatedEmailException; 22 | import com.flab.modu.users.exception.NotExistedUserException; 23 | import com.flab.modu.users.exception.WrongPasswordException; 24 | import com.flab.modu.users.service.LoginService; 25 | import com.flab.modu.users.service.UserService; 26 | import org.junit.jupiter.api.DisplayName; 27 | import org.junit.jupiter.api.Test; 28 | import org.junit.jupiter.api.extension.ExtendWith; 29 | import org.springframework.beans.factory.annotation.Autowired; 30 | import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; 31 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 32 | import org.springframework.boot.test.mock.mockito.MockBean; 33 | import org.springframework.http.MediaType; 34 | import org.springframework.restdocs.RestDocumentationExtension; 35 | import org.springframework.restdocs.payload.JsonFieldType; 36 | import org.springframework.test.context.ActiveProfiles; 37 | import org.springframework.test.web.servlet.MockMvc; 38 | 39 | @ExtendWith(RestDocumentationExtension.class) 40 | @AutoConfigureRestDocs 41 | @WebMvcTest(UserController.class) 42 | @ActiveProfiles("test") 43 | class UserControllerTest { 44 | 45 | @MockBean 46 | private UserService userService; 47 | 48 | @MockBean 49 | private LoginService loginService; 50 | 51 | @Autowired 52 | private MockMvc mockMvc; 53 | 54 | @Autowired 55 | private ObjectMapper objectMapper; 56 | 57 | @Test 58 | @DisplayName("회원가입 - 회원가입에 성공한다.") 59 | void createUser_successful() throws Exception { 60 | CreateRequest createRequest = getCreateRequest(); 61 | 62 | willDoNothing().given(userService).createUser(createRequest); 63 | 64 | mockMvc.perform(post("/users") 65 | .contentType(MediaType.APPLICATION_JSON) 66 | .content(objectMapper.writeValueAsString(createRequest))) 67 | .andDo(print()) 68 | .andExpect(status().isCreated()) 69 | .andDo(document("users/create/success", 70 | requestFields( 71 | fieldWithPath("email").type(JsonFieldType.STRING) 72 | .description("로그인 시 사용할 이메일"), 73 | fieldWithPath("password").type(JsonFieldType.STRING) 74 | .description("비밀번호"), 75 | fieldWithPath("name").type(JsonFieldType.STRING) 76 | .description("이름"), 77 | fieldWithPath("phoneNumber").type(JsonFieldType.STRING) 78 | .description("휴대폰 번호") 79 | ) 80 | )); 81 | 82 | then(userService).should().createUser(refEq(createRequest)); 83 | } 84 | 85 | @Test 86 | @DisplayName("회원가입 - 잘못된 입력 또는 중복된 이메일로 회원가입에 실패한다.") 87 | void createUser_failure() throws Exception { 88 | CreateRequest createRequest = getCreateRequest(); 89 | 90 | willThrow(new DuplicatedEmailException()).given(userService).createUser(any()); 91 | 92 | mockMvc.perform(post("/users") 93 | .contentType(MediaType.APPLICATION_JSON) 94 | .content(objectMapper.writeValueAsString(createRequest))) 95 | .andDo(print()) 96 | .andExpect(status().isConflict()) 97 | .andDo(document("users/create/failure", 98 | requestFields( 99 | fieldWithPath("email").type(JsonFieldType.STRING) 100 | .description("중복되지 않은 이메일"), 101 | fieldWithPath("password").type(JsonFieldType.STRING) 102 | .description("8자 이상 20자 이하의 비밀번호"), 103 | fieldWithPath("name").type(JsonFieldType.STRING) 104 | .description("2자 이상 10자 이하의 이름"), 105 | fieldWithPath("phoneNumber").type(JsonFieldType.STRING) 106 | .description("'-'을 제외한 휴대폰 번호") 107 | ) 108 | )); 109 | } 110 | 111 | @Test 112 | @DisplayName("로그인 - 로그인에 성공한다.") 113 | void login_success() throws Exception { 114 | LoginRequest loginRequest = getLoginRequest(); 115 | 116 | willDoNothing().given(loginService).login(loginRequest); 117 | 118 | mockMvc.perform(post("/users/login") 119 | .contentType(MediaType.APPLICATION_JSON) 120 | .content(objectMapper.writeValueAsString(loginRequest))) 121 | .andDo(print()) 122 | .andExpect(status().isOk()) 123 | .andDo(document("users/login/success", 124 | requestFields( 125 | fieldWithPath("email").type(JsonFieldType.STRING) 126 | .description("사용자 이메일"), 127 | fieldWithPath("password").type(JsonFieldType.STRING) 128 | .description("사용자 패스워드") 129 | ) 130 | )); 131 | 132 | then(loginService).should().login(refEq(loginRequest)); 133 | } 134 | 135 | @Test 136 | @DisplayName("로그인 - 이메일, 패스워드가 맞지 않아 로그인에 실패한다.") 137 | void login_failure() throws Exception { 138 | LoginRequest loginRequest = getLoginRequest(); 139 | 140 | willThrow(new NotExistedUserException()).given(loginService).login(any()); 141 | 142 | mockMvc.perform(post("/users/login") 143 | .contentType(MediaType.APPLICATION_JSON) 144 | .content(objectMapper.writeValueAsString(loginRequest))) 145 | .andDo(print()) 146 | .andExpect(status().isUnauthorized()) 147 | .andDo(document("users/login/failure", 148 | requestFields( 149 | fieldWithPath("email").type(JsonFieldType.STRING) 150 | .description("사용자 이메일"), 151 | fieldWithPath("password").type(JsonFieldType.STRING) 152 | .description("사용자 패스워드") 153 | ) 154 | )); 155 | } 156 | 157 | @Test 158 | @DisplayName("로그아웃 - 로그아웃에 성공한다.") 159 | public void logout_success() throws Exception { 160 | willDoNothing().given(loginService).logout(); 161 | 162 | mockMvc.perform(delete("/users/logout")) 163 | .andDo(print()) 164 | .andExpect(status().isOk()) 165 | .andDo(document("users/login/failure")); 166 | } 167 | 168 | @Test 169 | @DisplayName("회원탈퇴 - 회원탈퇴에 성공한다.") 170 | void deleteUser_successful() throws Exception { 171 | PasswordRequest passwordRequest = getPasswordRequest(); 172 | String password = passwordRequest.getPassword(); 173 | 174 | String email = "test@modu.com"; 175 | willAnswer(invocation -> email).given(loginService).getLoginUser(); 176 | willDoNothing().given(userService).delete(email, password); 177 | willDoNothing().given(loginService).logout(); 178 | 179 | mockMvc.perform(delete("/users") 180 | .header("email", email) 181 | .contentType(MediaType.APPLICATION_JSON) 182 | .content(objectMapper.writeValueAsString(passwordRequest))) 183 | .andDo(print()) 184 | .andExpect(status().isOk()) 185 | .andDo(document("users/delete/success", 186 | requestFields( 187 | fieldWithPath("password").type(JsonFieldType.STRING) 188 | .description("비밀번호") 189 | ) 190 | )); 191 | 192 | then(loginService).should().getLoginUser(); 193 | then(userService).should().delete(email, password); 194 | then(loginService).should().logout(); 195 | } 196 | 197 | @Test 198 | @DisplayName("회원탈퇴 - 요청정보가 일치하지 않아 회원탈퇴에 실패한다.") 199 | void deleteUser_failure() throws Exception { 200 | PasswordRequest passwordRequest = getPasswordRequest(); 201 | String password = passwordRequest.getPassword(); 202 | 203 | String email = "test@modu.com"; 204 | willAnswer(invocation -> email).given(loginService).getLoginUser(); 205 | willThrow(new WrongPasswordException()).given(userService).delete(email, password); 206 | 207 | mockMvc.perform(delete("/users") 208 | .header("email", email) 209 | .contentType(MediaType.APPLICATION_JSON) 210 | .content(objectMapper.writeValueAsString(passwordRequest))) 211 | .andDo(print()) 212 | .andExpect(status().isUnauthorized()) 213 | .andDo(document("users/delete/failure", 214 | requestFields( 215 | fieldWithPath("password").type(JsonFieldType.STRING) 216 | .description("비밀번호") 217 | ) 218 | )); 219 | 220 | then(loginService).should().getLoginUser(); 221 | } 222 | 223 | private CreateRequest getCreateRequest() { 224 | CreateRequest createRequest = CreateRequest.builder() 225 | .email("test123@modu.com") 226 | .password("test12344") 227 | .name("테스트네임") 228 | .phoneNumber("01012345678") 229 | .build(); 230 | return createRequest; 231 | } 232 | 233 | private LoginRequest getLoginRequest() { 234 | return LoginRequest.builder() 235 | .email("test123@modu.com") 236 | .password("test1234455") 237 | .build(); 238 | } 239 | 240 | private PasswordRequest getPasswordRequest() { 241 | return PasswordRequest.builder() 242 | .password("test12344") 243 | .build(); 244 | } 245 | } 246 | -------------------------------------------------------------------------------- /src/test/java/com/flab/modu/users/repository/UserRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.users.repository; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import com.flab.modu.global.config.JpaConfig; 6 | import com.flab.modu.users.controller.UserDto.UserResponse; 7 | import com.flab.modu.users.controller.UserDto.UserSearchCondition; 8 | import com.flab.modu.users.domain.common.UserRole; 9 | import com.flab.modu.users.domain.entity.User; 10 | import java.util.ArrayList; 11 | import java.util.List; 12 | import java.util.stream.Collectors; 13 | import java.util.stream.IntStream; 14 | import java.util.stream.Stream; 15 | import org.junit.jupiter.api.BeforeEach; 16 | import org.junit.jupiter.api.DisplayName; 17 | import org.junit.jupiter.api.Test; 18 | import org.springframework.beans.factory.annotation.Autowired; 19 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 20 | import org.springframework.context.annotation.Import; 21 | import org.springframework.data.domain.Page; 22 | import org.springframework.data.domain.PageRequest; 23 | import org.springframework.data.domain.Pageable; 24 | 25 | @DisplayName("JPA 연결 테스트") 26 | @Import(JpaConfig.class) 27 | @DataJpaTest 28 | class UserRepositoryTest { 29 | 30 | @Autowired 31 | private UserRepository userRepository; 32 | 33 | private final String EMAIL = "test@modu.com"; 34 | 35 | private final int TEST_SIZE = 10; 36 | 37 | @BeforeEach 38 | private void insertTestData() { 39 | List users = IntStream.range(0, 10) 40 | .mapToObj(i -> createUser(i)) 41 | .collect(Collectors.toList()); 42 | 43 | userRepository.saveAll(users); 44 | } 45 | 46 | @Test 47 | @DisplayName("db 연결 테스트") 48 | public void selectUser() throws Exception { 49 | // given 50 | 51 | // when 52 | List users = userRepository.findAll(); 53 | 54 | // then 55 | assertThat(users) 56 | .isNotNull() 57 | .hasSize(TEST_SIZE); 58 | } 59 | 60 | @Test 61 | @DisplayName("querydsl 테스트") 62 | public void searchUser_useQueryDsl() throws Exception { 63 | // given 64 | UserSearchCondition allCondition = UserSearchCondition.builder() 65 | .build(); 66 | 67 | String findEmail = getConcatData(EMAIL, 0); 68 | UserSearchCondition emailCondition = UserSearchCondition.builder() 69 | .email(findEmail) 70 | .build(); 71 | 72 | Pageable pageable = PageRequest.of(0, 10); 73 | 74 | // when 75 | Page allUsers = userRepository.searchByUsers(allCondition, pageable); 76 | Page user = userRepository.searchByUsers(emailCondition, pageable); 77 | UserResponse userResponse = user.stream().findFirst().get(); 78 | 79 | // then 80 | assertThat(allUsers.getTotalElements()).isEqualTo(TEST_SIZE); 81 | assertThat(user.getTotalElements()).isEqualTo(1); 82 | assertThat(userResponse.getEmail()).isEqualTo(findEmail); 83 | } 84 | 85 | private User createUser(int i) { 86 | return User.builder() 87 | .email(getConcatData(EMAIL, i)) 88 | .name(getConcatData("test", i)) 89 | .password(getConcatData("testPwd1234", i)) 90 | .role(UserRole.BUYER) 91 | .build(); 92 | } 93 | 94 | private String getConcatData(String data, int i) { 95 | return new StringBuilder(data).append(i).toString(); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/test/java/com/flab/modu/users/service/LoginServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.users.service; 2 | 3 | import static com.flab.modu.users.domain.common.UserConstant.EMAIL; 4 | import static org.junit.jupiter.api.Assertions.assertThrows; 5 | import static org.mockito.BDDMockito.given; 6 | import static org.mockito.BDDMockito.then; 7 | 8 | import com.flab.modu.users.controller.UserDto; 9 | import com.flab.modu.users.controller.UserDto.LoginRequest; 10 | import com.flab.modu.users.domain.common.UserRole; 11 | import com.flab.modu.users.domain.entity.User; 12 | import com.flab.modu.users.encoder.PasswordEncoder; 13 | import com.flab.modu.users.exception.NotExistedUserException; 14 | import com.flab.modu.users.repository.UserRepository; 15 | import java.util.Optional; 16 | import org.junit.jupiter.api.DisplayName; 17 | import org.junit.jupiter.api.Test; 18 | import org.junit.jupiter.api.extension.ExtendWith; 19 | import org.mockito.InjectMocks; 20 | import org.mockito.Mock; 21 | import org.mockito.junit.jupiter.MockitoExtension; 22 | import org.springframework.mock.web.MockHttpSession; 23 | 24 | @ExtendWith(MockitoExtension.class) 25 | class LoginServiceTest { 26 | 27 | @Mock 28 | private UserRepository userRepository; 29 | 30 | @InjectMocks 31 | private LoginService loginService; 32 | 33 | @Mock 34 | private PasswordEncoder passwordEncoder; 35 | 36 | @Mock 37 | private MockHttpSession session; 38 | 39 | private final String USER_EMAIL = "test123@modu.com"; 40 | private final String USER_PASSWORD = "testPwd"; 41 | 42 | @Test 43 | @DisplayName("로그인 - 이메일과 패스워드를 잘못 입력해 로그인에 실패한다..") 44 | public void notExistUser() throws Exception { 45 | // given 46 | LoginRequest loginRequest = loginRequest(); 47 | given(userRepository.findByEmailAndPassword(loginRequest.getEmail(), 48 | passwordEncoder.encrypt(loginRequest().getPassword()))).willReturn(Optional.empty()); 49 | 50 | // when 51 | assertThrows(NotExistedUserException.class, () -> loginService.login(loginRequest)); 52 | 53 | // then 54 | then(userRepository).should().findByEmailAndPassword(loginRequest.getEmail(), 55 | passwordEncoder.encrypt(loginRequest().getPassword())); 56 | then(session).shouldHaveNoInteractions(); 57 | } 58 | 59 | @Test 60 | @DisplayName("로그인 - 이메일, 패스워드가 일치하는 사용자는 로그인에 성공한다.") 61 | public void login_successful() throws Exception { 62 | // given 63 | LoginRequest loginRequest = loginRequest(); 64 | given(userRepository.findByEmailAndPassword(USER_EMAIL, passwordEncoder.encrypt(USER_PASSWORD))).willReturn(Optional.of(createUser())); 65 | 66 | // when 67 | loginService.login(loginRequest); 68 | 69 | // then 70 | then(userRepository).should().findByEmailAndPassword(USER_EMAIL, passwordEncoder.encrypt(USER_PASSWORD)); 71 | then(session).should().setAttribute(EMAIL, USER_EMAIL); 72 | } 73 | 74 | private UserDto.LoginRequest loginRequest() { 75 | return LoginRequest.builder() 76 | .email(USER_EMAIL) 77 | .password(USER_PASSWORD) 78 | .build(); 79 | } 80 | 81 | private User createUser() { 82 | return User.builder() 83 | .email(USER_EMAIL) 84 | .name("테스트네임") 85 | .password(USER_PASSWORD) 86 | .role(UserRole.BUYER) 87 | .phoneNumber("01012345678") 88 | .build(); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/test/java/com/flab/modu/users/service/UserServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.flab.modu.users.service; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertThrows; 4 | import static org.mockito.ArgumentMatchers.any; 5 | import static org.mockito.ArgumentMatchers.anyString; 6 | import static org.mockito.BDDMockito.given; 7 | import static org.mockito.BDDMockito.then; 8 | 9 | import com.flab.modu.users.controller.UserDto; 10 | import com.flab.modu.users.domain.common.UserRole; 11 | import com.flab.modu.users.domain.entity.User; 12 | import com.flab.modu.users.encoder.PasswordEncoder; 13 | import com.flab.modu.users.exception.DuplicatedEmailException; 14 | import com.flab.modu.users.exception.NotExistedUserException; 15 | import com.flab.modu.users.exception.WrongPasswordException; 16 | import com.flab.modu.users.repository.UserRepository; 17 | import java.util.Optional; 18 | import org.junit.jupiter.api.DisplayName; 19 | import org.junit.jupiter.api.Test; 20 | import org.junit.jupiter.api.extension.ExtendWith; 21 | import org.mockito.InjectMocks; 22 | import org.mockito.Mock; 23 | import org.mockito.junit.jupiter.MockitoExtension; 24 | 25 | @ExtendWith(MockitoExtension.class) 26 | class UserServiceTest { 27 | 28 | @Mock 29 | private UserRepository userRepository; 30 | 31 | @Mock 32 | PasswordEncoder passwordEncoder; 33 | 34 | @InjectMocks 35 | private UserService userService; 36 | 37 | private final String EXISTING_EMAIL = "test@modu.com"; 38 | 39 | private final String NOT_EXISTING_EMAIL = "test123@modu.com"; 40 | 41 | private final String CORRECT_PASSWORD = "test12345@"; 42 | 43 | private final String WRONG_PASSWORD = "test12345!"; 44 | 45 | @Test 46 | @DisplayName("정상적으로 회원가입에 성공한다.") 47 | public void createUser_successful() { 48 | // given 49 | UserDto.CreateRequest createRequest = createTestUserData(); 50 | given(userRepository.save(any(User.class))).willReturn(createUser()); 51 | 52 | // when 53 | userService.createUser(createRequest); 54 | 55 | // then 56 | then(userRepository).should().existsByEmail(anyString()); 57 | then(userRepository).should().save(any(User.class)); 58 | } 59 | 60 | @Test 61 | @DisplayName("이메일 중복은 회원가입에 실패한다.") 62 | public void emailDuplicated_createUser_failure() { 63 | // given 64 | UserDto.CreateRequest createRequest = createTestUserData(); 65 | given(userRepository.existsByEmail(EXISTING_EMAIL)).willReturn(true); 66 | 67 | // when 68 | assertThrows(DuplicatedEmailException.class, () -> userService.createUser(createRequest)); 69 | 70 | // then 71 | then(userRepository).should().existsByEmail(EXISTING_EMAIL); 72 | then(userRepository).shouldHaveNoMoreInteractions(); 73 | } 74 | 75 | @Test 76 | @DisplayName("회원탈퇴에 성공한다.") 77 | public void deleteUser_successful() throws Exception { 78 | // given 79 | User user = createUser(); 80 | given(userRepository.existsByEmail(EXISTING_EMAIL)).willReturn(true); 81 | given(userRepository.findByEmailAndPassword(EXISTING_EMAIL, 82 | passwordEncoder.encrypt(CORRECT_PASSWORD))).willReturn(Optional.of(user)); 83 | 84 | // when 85 | userService.delete(EXISTING_EMAIL, CORRECT_PASSWORD); 86 | 87 | // then 88 | then(userRepository).should().existsByEmail(EXISTING_EMAIL); 89 | then(userRepository).should() 90 | .findByEmailAndPassword(EXISTING_EMAIL, passwordEncoder.encrypt(CORRECT_PASSWORD)); 91 | then(userRepository).should().deleteByEmail(EXISTING_EMAIL); 92 | } 93 | 94 | @Test 95 | @DisplayName("이메일이 존재하지 않는 경우 회원탈퇴에 실패한다.") 96 | public void notExistEmail_deleteUser_failure() throws Exception { 97 | // given 98 | given(userRepository.existsByEmail(NOT_EXISTING_EMAIL)).willThrow(new NotExistedUserException()); 99 | 100 | // when 101 | assertThrows(NotExistedUserException.class, () -> userService.delete(NOT_EXISTING_EMAIL, CORRECT_PASSWORD)); 102 | 103 | // then 104 | then(userRepository).should().existsByEmail(NOT_EXISTING_EMAIL); 105 | then(userRepository).shouldHaveNoMoreInteractions(); 106 | } 107 | 108 | @Test 109 | @DisplayName("비밀번호를 틀린 경우 회원탈퇴에 실패한다.") 110 | public void wrongPassword_deleteUser_failure() throws Exception { 111 | // given 112 | User user = createUser(); 113 | given(userRepository.existsByEmail(EXISTING_EMAIL)).willReturn(true); 114 | given(userRepository.findByEmailAndPassword(EXISTING_EMAIL, 115 | passwordEncoder.encrypt(WRONG_PASSWORD))).willThrow( 116 | new WrongPasswordException()); 117 | 118 | // when 119 | assertThrows(WrongPasswordException.class, () -> userService.delete(EXISTING_EMAIL, WRONG_PASSWORD)); 120 | 121 | // then 122 | then(userRepository).should().existsByEmail(EXISTING_EMAIL); 123 | then(userRepository).should() 124 | .findByEmailAndPassword(EXISTING_EMAIL, passwordEncoder.encrypt(WRONG_PASSWORD)); 125 | then(userRepository).shouldHaveNoMoreInteractions(); 126 | } 127 | 128 | private UserDto.CreateRequest createTestUserData() { 129 | return UserDto.CreateRequest.builder() 130 | .email(EXISTING_EMAIL) 131 | .password(CORRECT_PASSWORD) 132 | .name("테스트네임") 133 | .phoneNumber("01012345678") 134 | .build(); 135 | } 136 | 137 | private User createUser() { 138 | return User.builder() 139 | .email(EXISTING_EMAIL) 140 | .name("테스트네임") 141 | .password(CORRECT_PASSWORD) 142 | .role(UserRole.BUYER) 143 | .phoneNumber("01012345678") 144 | .build(); 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /src/test/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | url: jdbc:h2:mem:modu 4 | username: sa 5 | password: 6 | driver-class-name: org.h2.Driver 7 | 8 | jpa: 9 | defer-datasource-initialization: true 10 | hibernate: 11 | ddl-auto: create 12 | database: h2 13 | show-sql: true 14 | 15 | database-platform: org.hibernate.dialect.H2Dialect 16 | 17 | properties: 18 | hibernate.format_sql: true 19 | 20 | logging: 21 | level: 22 | # ROOT: INFO 23 | # org.hibernate: DEBUG 24 | # org.hibernate.type.descriptor.sql.BasicBinder: TRACE 25 | # org.springframework.orm: TRACE 26 | # org.hibernate.type: TRACE 27 | org.springframework.transaction: TRACE 28 | # com.zaxxer.hikari: TRACE 29 | # com.mysql.cj.jdbc: TRACE --------------------------------------------------------------------------------