diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..097f9f9 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# Linux start script should use lf +/gradlew text eol=lf + +# These are Windows script files and should use crlf +*.bat text eol=crlf + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..228f79e --- /dev/null +++ b/.gitignore @@ -0,0 +1,205 @@ +# Created by https://www.toptal.com/developers/gitignore/api/java,macos,intellij,gradle +# Edit at https://www.toptal.com/developers/gitignore?templates=java,macos,intellij,gradle + +### Intellij ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +# https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +# SonarQube Plugin +# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +# Markdown Navigator plugin +# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea/**/markdown-navigator.xml +.idea/**/markdown-navigator-enh.xml +.idea/**/markdown-navigator/ + +# Cache file creation bug +# See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/$CACHE_FILE$ + +# CodeStream plugin +# https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +# Azure Toolkit for IntelliJ plugin +# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij +.idea/**/azureSettings.xml + +### Java ### +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + +### macOS ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### macOS Patch ### +# iCloud generated files +*.icloud + +### Gradle ### +.gradle +**/build/ +!src/**/build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Avoid ignore Gradle wrappper properties +!gradle-wrapper.properties + +# Cache of project +.gradletasknamecache + +# Eclipse Gradle plugin generated files +# Eclipse Core +.project +# JDT-specific (Eclipse Java Development Tools) +.classpath + +### Gradle Patch ### +# Java heap dump +*.hprof + +.idea + +# End of https://www.toptal.com/developers/gitignore/api/java,macos,intellij,gradle diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..5df6c9a --- /dev/null +++ b/build.gradle @@ -0,0 +1,23 @@ +plugins { + id 'java' +} + +group = 'meetcoder.study' +version = '1.0.0' + +java { + sourceCompatibility = '17' +} + +repositories { + mavenCentral() +} + +dependencies { + testImplementation 'org.junit.jupiter:junit-jupiter:5.10.2' + testImplementation 'org.assertj:assertj-core:3.25.3' +} + +test { + useJUnitPlatform() +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7f93135 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ac72c34 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..0adc8e1 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..8554d5e --- /dev/null +++ b/settings.gradle @@ -0,0 +1,14 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * The settings file is used to specify which projects to include in your build. + * For more detailed information on multi-project builds, please refer to https://docs.gradle.org/8.3/userguide/building_swift_projects.html in the Gradle documentation. + */ + +plugins { + // Apply the foojay-resolver plugin to allow automatic download of JDKs + id 'org.gradle.toolchains.foojay-resolver-convention' version '0.4.0' +} + +rootProject.name = 'java-baseball' +include('app') diff --git a/src/main/java/meetcoder/study/App.java b/src/main/java/meetcoder/study/App.java new file mode 100644 index 0000000..d9806d0 --- /dev/null +++ b/src/main/java/meetcoder/study/App.java @@ -0,0 +1,13 @@ +package meetcoder.study; + +import meetcoder.study.core.BaseballApplication; +import meetcoder.study.core.console.ConsoleBaseballApplication; + +public class App { + + public static void main(String[] args) { + BaseballApplication application = new ConsoleBaseballApplication(); + application.run(); + } + +} diff --git a/src/main/java/meetcoder/study/core/BaseballApplication.java b/src/main/java/meetcoder/study/core/BaseballApplication.java new file mode 100644 index 0000000..3ec2a2e --- /dev/null +++ b/src/main/java/meetcoder/study/core/BaseballApplication.java @@ -0,0 +1,9 @@ +package meetcoder.study.core; + +public interface BaseballApplication { + + void run(); + + void exit(); + +} diff --git a/src/main/java/meetcoder/study/core/BaseballGame.java b/src/main/java/meetcoder/study/core/BaseballGame.java new file mode 100644 index 0000000..a9a6c70 --- /dev/null +++ b/src/main/java/meetcoder/study/core/BaseballGame.java @@ -0,0 +1,7 @@ +package meetcoder.study.core; + +public interface BaseballGame { + + void play(); + +} diff --git a/src/main/java/meetcoder/study/core/command/Command.java b/src/main/java/meetcoder/study/core/command/Command.java new file mode 100644 index 0000000..7bfb9ef --- /dev/null +++ b/src/main/java/meetcoder/study/core/command/Command.java @@ -0,0 +1,7 @@ +package meetcoder.study.core.command; + +public interface Command { + + void excute(); + +} diff --git a/src/main/java/meetcoder/study/core/command/CommandFactory.java b/src/main/java/meetcoder/study/core/command/CommandFactory.java new file mode 100644 index 0000000..26493a8 --- /dev/null +++ b/src/main/java/meetcoder/study/core/command/CommandFactory.java @@ -0,0 +1,22 @@ +package meetcoder.study.core.command; + +import java.util.HashMap; +import java.util.Map; + +public class CommandFactory { + + private final Map commandMap; + + public CommandFactory(Map commandMap) { + this.commandMap = new HashMap<>(commandMap); + } + + public Command getCommand(String key) { + if (commandMap.containsKey(key)) { + return commandMap.get(key); + } + + throw new IllegalArgumentException("존재하지 않는 명령어입니다."); + } + +} diff --git a/src/main/java/meetcoder/study/core/command/ExitApplicationCommand.java b/src/main/java/meetcoder/study/core/command/ExitApplicationCommand.java new file mode 100644 index 0000000..8b016ed --- /dev/null +++ b/src/main/java/meetcoder/study/core/command/ExitApplicationCommand.java @@ -0,0 +1,18 @@ +package meetcoder.study.core.command; + +import meetcoder.study.core.BaseballApplication; + +public class ExitApplicationCommand implements Command { + + private final BaseballApplication application; + + public ExitApplicationCommand(BaseballApplication application) { + this.application = application; + } + + @Override + public void excute() { + application.exit(); + } + +} diff --git a/src/main/java/meetcoder/study/core/command/PlayGameCommand.java b/src/main/java/meetcoder/study/core/command/PlayGameCommand.java new file mode 100644 index 0000000..a9f5524 --- /dev/null +++ b/src/main/java/meetcoder/study/core/command/PlayGameCommand.java @@ -0,0 +1,18 @@ +package meetcoder.study.core.command; + +import meetcoder.study.core.BaseballGame; + +public class PlayGameCommand implements Command { + + private final BaseballGame game; + + public PlayGameCommand(BaseballGame game) { + this.game = game; + } + + @Override + public void excute() { + game.play(); + } + +} diff --git a/src/main/java/meetcoder/study/core/console/ConsoleBaseballApplication.java b/src/main/java/meetcoder/study/core/console/ConsoleBaseballApplication.java new file mode 100644 index 0000000..19599ae --- /dev/null +++ b/src/main/java/meetcoder/study/core/console/ConsoleBaseballApplication.java @@ -0,0 +1,57 @@ +package meetcoder.study.core.console; + +import java.util.Map; +import meetcoder.study.core.BaseballApplication; +import meetcoder.study.core.command.Command; +import meetcoder.study.core.command.CommandFactory; +import meetcoder.study.core.command.ExitApplicationCommand; +import meetcoder.study.core.command.PlayGameCommand; +import meetcoder.study.service.RandomBallNumbersGenerator; +import meetcoder.study.view.ConsoleInputView; +import meetcoder.study.view.ConsoleOutputView; + +public class ConsoleBaseballApplication implements BaseballApplication { + + private final ConsoleInputView inputView; + private final ConsoleOutputView outputView; + private final CommandFactory commandFactory; + private boolean isRunning; + + public ConsoleBaseballApplication() { + this.inputView = new ConsoleInputView(); + this.outputView = new ConsoleOutputView(); + this.commandFactory = new CommandFactory( + Map.of( + "1", new PlayGameCommand( + new ConsoleBaseballGame( + inputView, outputView, new RandomBallNumbersGenerator())), + "9", new ExitApplicationCommand(this) + ) + ); + } + + @Override + public void run() { + isRunning = true; + while (isRunning) { + processCommand(); + } + } + + @Override + public void exit() { + outputView.displayGoodbyeMessage(); + isRunning = false; + } + + private void processCommand() { + try { + outputView.displayManual(); + Command command = inputView.getCommand(commandFactory); + command.excute(); + } catch (Exception ex) { + outputView.displayError(ex); + } + } + +} diff --git a/src/main/java/meetcoder/study/core/console/ConsoleBaseballGame.java b/src/main/java/meetcoder/study/core/console/ConsoleBaseballGame.java new file mode 100644 index 0000000..48821c8 --- /dev/null +++ b/src/main/java/meetcoder/study/core/console/ConsoleBaseballGame.java @@ -0,0 +1,56 @@ +package meetcoder.study.core.console; + +import meetcoder.study.core.BaseballGame; +import meetcoder.study.model.BallNumbers; +import meetcoder.study.model.BaseballGuessResult; +import meetcoder.study.service.BallNumbersGenerator; +import meetcoder.study.view.ConsoleInputView; +import meetcoder.study.view.ConsoleOutputView; + +public class ConsoleBaseballGame implements BaseballGame { + + private final ConsoleInputView inputView; + private final ConsoleOutputView outputView; + private final BallNumbersGenerator ballNumbersGenerator; + private BallNumbers targetNumbers; + private boolean isRunning; + + public ConsoleBaseballGame( + ConsoleInputView inputView, ConsoleOutputView outputView, + BallNumbersGenerator ballNumbersGenerator + ) { + this.inputView = inputView; + this.outputView = outputView; + this.ballNumbersGenerator = ballNumbersGenerator; + } + + @Override + public void play() { + isRunning = true; + targetNumbers = ballNumbersGenerator.generate(); + outputView.displaySetUpComplete(); + while (isRunning) { + guess(); + } + } + + private void guess() { + try { + outputView.displayNumberInputRequest(); + BallNumbers guessedNumbers = inputView.readBaseballNumber(); + BaseballGuessResult result = targetNumbers.evaluateGuess(guessedNumbers); + outputView.printBaseballResult(result); + if (result.isAllStrike()) { + end(); + } + } catch (Exception ex) { + outputView.displayError(ex); + } + } + + private void end() { + outputView.displayGameOver(); + isRunning = false; + } + +} diff --git a/src/main/java/meetcoder/study/model/BallNumber.java b/src/main/java/meetcoder/study/model/BallNumber.java new file mode 100644 index 0000000..5c1fb11 --- /dev/null +++ b/src/main/java/meetcoder/study/model/BallNumber.java @@ -0,0 +1,42 @@ +package meetcoder.study.model; + +import static meetcoder.study.util.Validator.checkArgument; + +import java.util.Objects; + +public class BallNumber { + + public static final int MIN_BALL_NUMBER = 1; + public static final int MAX_BALL_NUMBER = 9; + private final int number; + + private BallNumber(int number) { + this.number = number; + } + + public static BallNumber of(int number) { + checkArgument( + number >= MIN_BALL_NUMBER && number <= MAX_BALL_NUMBER, + "BallNumber은 " + MIN_BALL_NUMBER + "~" + MAX_BALL_NUMBER + "사이의 숫자여야 합니다." + ); + return new BallNumber(number); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + BallNumber that = (BallNumber) o; + return number == that.number; + } + + @Override + public int hashCode() { + return Objects.hash(number); + } + +} diff --git a/src/main/java/meetcoder/study/model/BallNumbers.java b/src/main/java/meetcoder/study/model/BallNumbers.java new file mode 100644 index 0000000..8e976b4 --- /dev/null +++ b/src/main/java/meetcoder/study/model/BallNumbers.java @@ -0,0 +1,75 @@ +package meetcoder.study.model; + +import static meetcoder.study.model.BallNumber.MAX_BALL_NUMBER; +import static meetcoder.study.model.BallNumber.MIN_BALL_NUMBER; +import static meetcoder.study.util.Validator.checkArgument; + +import java.util.List; +import java.util.Objects; + +public class BallNumbers { + + public static final int BALL_NUMBERS_SIZE = 3; + private final List numbers; + + private BallNumbers(List numbers) { + validate(numbers); + this.numbers = numbers.stream() + .map(BallNumber::of) + .toList(); + } + + public static BallNumbers of(List numbers) { + return new BallNumbers(numbers); + } + + public BaseballGuessResult evaluateGuess(BallNumbers guessedNumber) { + int strike = 0; + int ball = 0; + + for (int i = 0; i < BALL_NUMBERS_SIZE; i++) { + GuessResultType result = evaluateSingleGuess(guessedNumber.numbers.get(i), i); + if (Objects.equals(result, GuessResultType.STRIKE)) { + strike++; + } else if (Objects.equals(result, GuessResultType.BALL)) { + ball++; + } + } + + return new BaseballGuessResult(strike, ball); + } + + private GuessResultType evaluateSingleGuess(BallNumber number, int position) { + if (isStrike(number, position)) { + return GuessResultType.STRIKE; + } + + if (isBall(number, position)) { + return GuessResultType.BALL; + } + + return GuessResultType.NOTHING; + } + + private boolean isStrike(BallNumber number, int position) { + return position < BALL_NUMBERS_SIZE && numbers.get(position) + .equals(number); + } + + private boolean isBall(BallNumber number, int position) { + return !isStrike(number, position) && numbers.contains(number); + } + + private void validate(List numbers) { + long count = numbers.stream() + .distinct() + .count(); + + checkArgument( + count == BALL_NUMBERS_SIZE, + "야구 숫자는 " + MIN_BALL_NUMBER + "~" + MAX_BALL_NUMBER + "사이의 서로 다른 " + BALL_NUMBERS_SIZE + + "자리 숫자여야 합니다." + ); + } + +} diff --git a/src/main/java/meetcoder/study/model/BaseballGuessResult.java b/src/main/java/meetcoder/study/model/BaseballGuessResult.java new file mode 100644 index 0000000..5ed1a53 --- /dev/null +++ b/src/main/java/meetcoder/study/model/BaseballGuessResult.java @@ -0,0 +1,50 @@ +package meetcoder.study.model; + +import static meetcoder.study.model.BallNumbers.BALL_NUMBERS_SIZE; +import static meetcoder.study.model.GuessResultType.BALL; +import static meetcoder.study.model.GuessResultType.NOTHING; +import static meetcoder.study.model.GuessResultType.STRIKE; + +public record BaseballGuessResult( + int strikeCount, + int ballCount +) { + + public boolean isAllStrike() { + return strikeCount == BALL_NUMBERS_SIZE; + } + + public String summary() { + if (isNothing()) { + return NOTHING.getName(); + } + + StringBuilder sb = new StringBuilder(); + if (hasBall()) { + sb.append(ballCount) + .append(BALL.getName()) + .append(" "); + } + + if (hasStrike()) { + sb.append(strikeCount) + .append(STRIKE.getName()); + } + + return sb.toString() + .trim(); + } + + private boolean isNothing() { + return strikeCount == 0 && ballCount == 0; + } + + private boolean hasStrike() { + return strikeCount > 0; + } + + private boolean hasBall() { + return ballCount > 0; + } + +} diff --git a/src/main/java/meetcoder/study/model/GuessResultType.java b/src/main/java/meetcoder/study/model/GuessResultType.java new file mode 100644 index 0000000..d1d77d4 --- /dev/null +++ b/src/main/java/meetcoder/study/model/GuessResultType.java @@ -0,0 +1,17 @@ +package meetcoder.study.model; + +public enum GuessResultType { + NOTHING("낫싱"), + STRIKE("스트라이크"), + BALL("볼"); + + private final String name; + + GuessResultType(String name) { + this.name = name; + } + + public String getName() { + return name; + } +} diff --git a/src/main/java/meetcoder/study/service/BallNumbersGenerator.java b/src/main/java/meetcoder/study/service/BallNumbersGenerator.java new file mode 100644 index 0000000..17a1c41 --- /dev/null +++ b/src/main/java/meetcoder/study/service/BallNumbersGenerator.java @@ -0,0 +1,9 @@ +package meetcoder.study.service; + +import meetcoder.study.model.BallNumbers; + +public interface BallNumbersGenerator { + + BallNumbers generate(); + +} diff --git a/src/main/java/meetcoder/study/service/RandomBallNumbersGenerator.java b/src/main/java/meetcoder/study/service/RandomBallNumbersGenerator.java new file mode 100644 index 0000000..468cb98 --- /dev/null +++ b/src/main/java/meetcoder/study/service/RandomBallNumbersGenerator.java @@ -0,0 +1,33 @@ +package meetcoder.study.service; + +import static meetcoder.study.model.BallNumber.MAX_BALL_NUMBER; +import static meetcoder.study.model.BallNumber.MIN_BALL_NUMBER; +import static meetcoder.study.model.BallNumbers.BALL_NUMBERS_SIZE; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import meetcoder.study.model.BallNumbers; + +public class RandomBallNumbersGenerator implements BallNumbersGenerator { + + @Override + public BallNumbers generate() { + List numbers = createNumberRange(MIN_BALL_NUMBER, MAX_BALL_NUMBER); + Collections.shuffle(numbers); + + return BallNumbers.of( + new ArrayList<>(numbers.subList(0, BALL_NUMBERS_SIZE))); + } + + private List createNumberRange(int min, int max) { + List numbers = new ArrayList<>(); + + for (int i = min; i <= max; i++) { + numbers.add(i); + } + + return numbers; + } + +} diff --git a/src/main/java/meetcoder/study/util/Validator.java b/src/main/java/meetcoder/study/util/Validator.java new file mode 100644 index 0000000..784fe70 --- /dev/null +++ b/src/main/java/meetcoder/study/util/Validator.java @@ -0,0 +1,15 @@ +package meetcoder.study.util; + +public final class Validator { + + private Validator() { + // 유틸리티 클래스 + } + + public static void checkArgument(boolean expression, String message) { + if (!expression) { + throw new IllegalArgumentException(message); + } + } + +} diff --git a/src/main/java/meetcoder/study/view/ConsoleInputView.java b/src/main/java/meetcoder/study/view/ConsoleInputView.java new file mode 100644 index 0000000..f7f4ac1 --- /dev/null +++ b/src/main/java/meetcoder/study/view/ConsoleInputView.java @@ -0,0 +1,43 @@ +package meetcoder.study.view; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.List; +import meetcoder.study.core.command.Command; +import meetcoder.study.core.command.CommandFactory; +import meetcoder.study.model.BallNumbers; + +public class ConsoleInputView { + + private static final BufferedReader reader = new BufferedReader( + new InputStreamReader(System.in)); + + public Command getCommand(CommandFactory commandFactory) { + return commandFactory.getCommand(readString()); + } + + public BallNumbers readBaseballNumber() { + return BallNumbers.of(readInts()); + } + + private String readString() { + try { + return reader.readLine(); + } catch (Exception e) { + throw new IllegalArgumentException("입력값을 읽을 수 없습니다."); + } + } + + private List readInts() { + try { + return readString().chars() + .boxed() + .map(Character::getNumericValue) + .toList(); + } catch (Exception e) { + throw new IllegalArgumentException("숫자를 입력해주세요."); + } + } + + +} diff --git a/src/main/java/meetcoder/study/view/ConsoleMessage.java b/src/main/java/meetcoder/study/view/ConsoleMessage.java new file mode 100644 index 0000000..1c8e556 --- /dev/null +++ b/src/main/java/meetcoder/study/view/ConsoleMessage.java @@ -0,0 +1,22 @@ +package meetcoder.study.view; + +import static meetcoder.study.model.BallNumbers.BALL_NUMBERS_SIZE; + +final class ConsoleMessage { + + /** + * 어플리케이션 + */ + static final String COMMAND_DESCRIPTION = "게임을 새로 시작하려면 1, 종료하려면 9를 입력하세요."; + static final String GOOD_BYE_MESSAGE = "애플리케이션이 종료되었습니다."; + + /** + * 야구 게임 + */ + static final String SETUP_MESSAGE = "컴퓨터가 숫자를 뽑았습니다."; + static final String NUMBER_INPUT_MESSAGE = "숫자를 입력해주세요"; + static final String CLEAR_MESSAGE = + BALL_NUMBERS_SIZE + "개의 숫자를 모두 맞히셨습니다."; + static final String END_MESSAGE = "게임 종료"; + +} diff --git a/src/main/java/meetcoder/study/view/ConsoleOutputView.java b/src/main/java/meetcoder/study/view/ConsoleOutputView.java new file mode 100644 index 0000000..2a032b8 --- /dev/null +++ b/src/main/java/meetcoder/study/view/ConsoleOutputView.java @@ -0,0 +1,64 @@ +package meetcoder.study.view; + +import static meetcoder.study.view.ConsoleMessage.CLEAR_MESSAGE; +import static meetcoder.study.view.ConsoleMessage.COMMAND_DESCRIPTION; +import static meetcoder.study.view.ConsoleMessage.END_MESSAGE; +import static meetcoder.study.view.ConsoleMessage.GOOD_BYE_MESSAGE; +import static meetcoder.study.view.ConsoleMessage.NUMBER_INPUT_MESSAGE; +import static meetcoder.study.view.ConsoleMessage.SETUP_MESSAGE; + +import meetcoder.study.model.BaseballGuessResult; + +public class ConsoleOutputView { + + public void displayManual() { + println(COMMAND_DESCRIPTION); + } + + public void displayError(Exception ex) { + println("⚠️" + ex.getMessage()); + } + + public void displayGoodbyeMessage() { + emptyLine(); + println(GOOD_BYE_MESSAGE); + } + + public void displaySetUpComplete() { + emptyLine(); + println(SETUP_MESSAGE); + emptyLine(); + } + + public void displayNumberInputRequest() { + print(NUMBER_INPUT_MESSAGE + " : "); + } + + public void displayGameOver() { + emptyLine(); + println(CLEAR_MESSAGE); + printWithDashLine(END_MESSAGE); + emptyLine(); + } + + public void printBaseballResult(BaseballGuessResult result) { + println(result.summary()); + } + + private void println(String message) { + System.out.println(message); + } + + private void print(String message) { + System.out.print(message); + } + + public void printWithDashLine(String message) { + System.out.println("-------" + message + "-------"); + } + + private void emptyLine() { + System.out.println(); + } + +} diff --git a/src/test/java/meetcoder/study/core/command/CommandFactoryTest.java b/src/test/java/meetcoder/study/core/command/CommandFactoryTest.java new file mode 100644 index 0000000..c8f9610 --- /dev/null +++ b/src/test/java/meetcoder/study/core/command/CommandFactoryTest.java @@ -0,0 +1,46 @@ +package meetcoder.study.core.command; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + +import java.util.HashMap; +import java.util.Map; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class CommandFactoryTest { + + @DisplayName("유효한 키로 Command를 가져올 수 있다.") + @Test + void shouldReturnCommandForValidKey() { + // given + String key = "key"; + Command mockCommand = () -> { + }; + CommandFactory commandFactory = new CommandFactory(Map.of(key, mockCommand)); + + // when + Command command = commandFactory.getCommand(key); + + // then + assertThat(command).isEqualTo(mockCommand); + } + + @DisplayName("존재하지 않는 키로 Command를를 가져오려고 하면 예외가 발생한다.") + @Test + void shouldThrowExceptionForInvalidKey() { + // given + CommandFactory commandFactory = new CommandFactory(new HashMap<>()); + + // when + ThrowingCallable getCommand = () -> commandFactory.getCommand("invalidKey"); + + // when & then + assertThatIllegalArgumentException() + .isThrownBy(getCommand) + .withMessage("존재하지 않는 명령어입니다."); + } + + +} diff --git a/src/test/java/meetcoder/study/model/BallNumberTest.java b/src/test/java/meetcoder/study/model/BallNumberTest.java new file mode 100644 index 0000000..b573c89 --- /dev/null +++ b/src/test/java/meetcoder/study/model/BallNumberTest.java @@ -0,0 +1,55 @@ +package meetcoder.study.model; + +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class BallNumberTest { + + @DisplayName("1~9 사이의 숫자로 BallNumber를 생성한다.") + @ParameterizedTest + @ValueSource(ints = {1, 2, 3, 4, 5, 6, 7, 8, 9}) + void shouldCreateBallNumberWithValidNumber(int number) { + // when + BallNumber created = BallNumber.of(number); + + // then + assertNotNull(created); + } + + @DisplayName("1~9 사이의 숫자가 아닌 경우, BallNumber를 생성할 수 없다.") + @ParameterizedTest + @ValueSource(ints = {-1, 0, 10}) + void shouldThrowExceptionWhenNumberIsOutOfRange(int invalidNumber) { + // given + + // when + ThrowingCallable of = () -> BallNumber.of(invalidNumber); + + // then + assertThatIllegalArgumentException() + .isThrownBy(of) + .withMessage("BallNumber은 1~9사이의 숫자여야 합니다."); + } + + @DisplayName("같은 숫자를 가진 BallNumber는 동등한 객체이다.") + @Test + void ballNumbersWithSameValueShouldBeEqual() { + // given + BallNumber ballNumber1 = BallNumber.of(1); + BallNumber ballNumber2 = BallNumber.of(1); + + // when + boolean isEqual = ballNumber1.equals(ballNumber2); + + // then + assertTrue(isEqual); + } + +} diff --git a/src/test/java/meetcoder/study/model/BallNumbersTest.java b/src/test/java/meetcoder/study/model/BallNumbersTest.java new file mode 100644 index 0000000..5b8269d --- /dev/null +++ b/src/test/java/meetcoder/study/model/BallNumbersTest.java @@ -0,0 +1,111 @@ +package meetcoder.study.model; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class BallNumbersTest { + + @DisplayName("1 ~ 9사이의 서로 다른 3개의 숫자로 BallNumbers를 생성한다.") + @Test + void shouldCreateBallNumbersWithValidNumbers() { + // when + BallNumbers created = BallNumbers.of(List.of(1, 2, 3)); + + // then + assertNotNull(created); + } + + @DisplayName("1 ~ 9사이의 숫자가 아닌 경우, BallNumbers를 생성할 수 없다.") + @Test + void shouldThrowExceptionWhenNumbersAreOutOfRange() { + // when + ThrowingCallable of = () -> BallNumbers.of(List.of(1, 2, 10)); + + // then + assertThatIllegalArgumentException() + .isThrownBy(of) + .withMessage("BallNumber은 1~9사이의 숫자여야 합니다."); + } + + @DisplayName("중복된 숫자가 있는 경우, BallNumbers를 생성할 수 없다.") + @Test + void shouldThrowExceptionWhenNumbersAreDuplicated() { + // when + ThrowingCallable of = () -> BallNumbers.of(List.of(1, 1, 2)); + + // then + assertThatIllegalArgumentException() + .isThrownBy(of) + .withMessage("야구 숫자는 1~9사이의 서로 다른 3자리 숫자여야 합니다."); + } + + @DisplayName("BallNumbers가 가지고 있는 숫자를 추측하여, 추측 결과를 확인한다. (Case. 3스트라이크)") + @Test + void shouldReturnThreeStrikesWhenAllNumbersAndPositionsMatch() { + // given + BallNumbers target = BallNumbers.of(List.of(1, 2, 3)); + BallNumbers guessedNumber = BallNumbers.of(List.of(1, 2, 3)); + + // when + BaseballGuessResult result = target.evaluateGuess(guessedNumber); + + // then + assertTrue(result.isAllStrike()); + assertThat(result.ballCount()).isEqualTo(0); + assertThat(result.strikeCount()).isEqualTo(3); + } + + @DisplayName("BallNumbers가 가지고 있는 숫자를 추측하여, 추측 결과를 확인한다.(Case. 3볼)") + @Test + void shouldReturnThreeBallsWhenAllNumbersMatchButPositionsDoNot() { + // given + BallNumbers target = BallNumbers.of(List.of(1, 2, 3)); + BallNumbers guessedNumber = BallNumbers.of(List.of(3, 1, 2)); + + // when + BaseballGuessResult result = target.evaluateGuess(guessedNumber); + + // then + assertThat(result.ballCount()).isEqualTo(3); + assertThat(result.strikeCount()).isEqualTo(0); + } + + @DisplayName("BallNumbers가 가지고 있는 숫자를 추측하여, 추측 결과를 확인한다.(Case. 2볼 1스트라이크)") + @Test + void shouldReturnTwoBallsAndOneStrikeWhenTwoNumbersMatchButOnlyOnePositionMatches() { + // given + BallNumbers target = BallNumbers.of(List.of(1, 2, 3)); + BallNumbers guessedNumber = BallNumbers.of(List.of(1, 3, 2)); + + // when + BaseballGuessResult result = target.evaluateGuess(guessedNumber); + + // then + assertThat(result.ballCount()).isEqualTo(2); + assertThat(result.strikeCount()).isEqualTo(1); + } + + @DisplayName("BallNumbers가 가지고 있는 숫자를 추측하여, 추측 결과를 확인한다.(Case. 낫싱)") + @Test + void shouldReturnNothingWhenNoNumbersMatch() { + // given + BallNumbers target = BallNumbers.of(List.of(1, 2, 3)); + BallNumbers guessedNumber = BallNumbers.of(List.of(4, 5, 6)); + + // when + BaseballGuessResult result = target.evaluateGuess(guessedNumber); + + // then + assertThat(result.ballCount()).isEqualTo(0); + assertThat(result.strikeCount()).isEqualTo(0); + } + + +} diff --git a/src/test/java/meetcoder/study/model/BaseballGuessResultTest.java b/src/test/java/meetcoder/study/model/BaseballGuessResultTest.java new file mode 100644 index 0000000..f8f35ef --- /dev/null +++ b/src/test/java/meetcoder/study/model/BaseballGuessResultTest.java @@ -0,0 +1,31 @@ +package meetcoder.study.model; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class BaseballGuessResultTest { + + @DisplayName("스트라이크 수가 3개인 경우, isAllStrike가 true이다.") + @Test + void shouldReturnTrueWhenAllThreeAreStrikes() { + // when + BaseballGuessResult result = new BaseballGuessResult(3, 0); + + // then + assertTrue(result.isAllStrike()); + } + + @DisplayName("추측 결과를 요약한다.") + @Test + void shouldSummarizeGuessResultCorrectly() { + // when + BaseballGuessResult result = new BaseballGuessResult(1, 2); + + // then + assertEquals(result.summary(), "2볼 1스트라이크"); + } + +} diff --git a/src/test/java/meetcoder/study/service/RandomBallNumbersGeneratorTest.java b/src/test/java/meetcoder/study/service/RandomBallNumbersGeneratorTest.java new file mode 100644 index 0000000..f0632ef --- /dev/null +++ b/src/test/java/meetcoder/study/service/RandomBallNumbersGeneratorTest.java @@ -0,0 +1,29 @@ +package meetcoder.study.service; + +import static org.assertj.core.api.Assertions.assertThat; + +import meetcoder.study.model.BallNumbers; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class RandomBallNumbersGeneratorTest { + + RandomBallNumbersGenerator randomBallNumbersGenerator; + + @BeforeEach + void setUp() { + randomBallNumbersGenerator = new RandomBallNumbersGenerator(); + } + + @DisplayName("랜덤으로 생성된 BallNumbers를 반환한다.") + @Test + void generateBallNumbersRandomly() { + // when + BallNumbers generated = randomBallNumbersGenerator.generate(); + + // then + assertThat(generated).isNotNull(); + } + +} diff --git a/src/test/java/meetcoder/study/util/ValidatorTest.java b/src/test/java/meetcoder/study/util/ValidatorTest.java new file mode 100644 index 0000000..831892d --- /dev/null +++ b/src/test/java/meetcoder/study/util/ValidatorTest.java @@ -0,0 +1,34 @@ +package meetcoder.study.util; + +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class ValidatorTest { + + @DisplayName("표현식이 true인 경우, 예외가 발생하지 않는다.") + @Test + void checkArgumentTrue() { + // then + assertDoesNotThrow(() -> Validator.checkArgument(true, "예외가 발생하면 안됩니다.")); + } + + @DisplayName("표현식이 false인 경우, 예외가 발생한다.") + @Test + void checkArgumentFalse() { + // given + String errorMessage = "예외가 발생해야 합니다."; + + // when + ThrowingCallable checkArgument = () -> Validator.checkArgument(false, errorMessage); + + // then + assertThatIllegalArgumentException() + .isThrownBy(checkArgument) + .withMessage(errorMessage); + } + +}