Skip to content

[이예진] 계산기 구현 2,3,4단계 #89

New issue

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

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

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: yaevrai
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,30 @@
# java-calculator

계산기 미션 저장소

## level1
### 간단한 사칙연산 계산기 구현

요구사항
- 인자 2개를 받아 사칙연산을 할 수 있는 계산기를 구현한다.
- 사칙연산과 매칭되는 4개의 메서드를 제공한다.
- 계산된 결과는 정수를 반환한다.

## level2
### 구현한 사칙연산 계산기 테스트

요구사항
- 구현한 초간단 계산기가 예상한대로 동작하는지 Junit5를 활용하여 테스트를 자동화한다.


## level3
### 문자열 계산기 구현
요구사항
- 쉼표(,) 또는 콜론(:)을 구분자로 가지는 문자열을 전달하는 경우 구분자를 기준으로 분리한 각 숫자의 합을 반환 (예: “” => 0, "1,2" => 3, "1,2,3" => 6, “1,2:3” => 6)
- 앞의 기본 구분자(쉼표, 콜론)외에 커스텀 구분자를 지정할 수 있다. 커스텀 구분자는 문자열 앞부분의 “//”와 “\n” 사이에 위치하는 문자를 커스텀 구분자로 사용한다. 예를 들어 “//;\n1;2;3”과 같이 값을 입력할 경우 커스텀 구분자는 세미콜론(;)이며, 결과 값은 6이 반환되어야 한다.
- 문자열 계산기에 숫자 이외의 값 또는 음수를 전달하는 경우 RuntimeException 예외를 throw한다.

## level4
### 문자열 계산기 구현 리팩토링
- 기존 JUnit5로 작성되어 있던 단위 테스트를 AssertJ로 리팩터링한다.
JUnit5에서 제공하는 기능과 AssertJ에서 제공하는 기능을 사용해보고, 어떠한 차이가 있는지 경험한다.
Comment on lines +4 to +30

Choose a reason for hiding this comment

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

요구사항 정리 👍
추후 이 문서가 이정표가 되어 줄 것 같네요!

2 changes: 2 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ repositories {

dependencies {
testImplementation platform('org.junit:junit-bom:5.9.1')
testImplementation platform('org.assertj:assertj-bom:3.25.1')
testImplementation('org.junit.jupiter:junit-jupiter')
testImplementation('org.assertj:assertj-core')
}

test {
Expand Down
8 changes: 4 additions & 4 deletions src/main/java/Calculator.java
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
public class Calculator {
int add(int a, int b) {
public int add(int a, int b) {
return a + b;
}

int subtract(int a, int b) {
public int subtract(int a, int b) {
return a - b;
}

int multiply(int a, int b) {
public int multiply(int a, int b) {
return a * b;
}

int divide(int a, int b) {
public int divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("0으로 나눌 수 없습니다.");
}
Expand Down
68 changes: 68 additions & 0 deletions src/main/java/StringCalculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@

public class StringCalculator {

public int calculate(String input) {

if (input == null || input.trim().isEmpty()) {
return 0;
}

// 지정 구분자
String separator = "[,;]";
String numbers = input;

/*
* 커스텀 구분자 체크
* 1. 입력받은 문자열이 //로 시작하면 \n 으로 끝나는 사이의 값을 구분자로 지정한다.
* 2. 커스텀 구분자가 정규 표현식으로 사용되는 문자일 경우 이스케이프 처리한다.
*/
if (input.startsWith("//")) {
int newSeparatorIndex = input.indexOf("\n");

String customSeparator = input.substring(2, newSeparatorIndex).trim();

// 정규식 특수문자 앞에 /를 붙인다. [\\\\^$.|?*+()\\[\\]{}]는 정규식 특수문자를 모두 찾는 패턴, \\\\는 자바에서 \를 앞에 붙여주는 표현
customSeparator = customSeparator.replaceAll("[\\\\^$.|?*+()\\[\\]{}]", "\\\\$0");

separator = customSeparator + "|,|;";

numbers = input.substring(newSeparatorIndex + 1).trim();
}

if (numbers.isEmpty()) {
return 0;
}

String[] numbersArray = numbers.split(separator);

int sum = 0;

for (String number : numbersArray) {
if (!isNumeric(number)) {
throw new RuntimeException("숫자가 아닌 값이 포함되어있습니다.");
}

sum += Integer.parseInt(number);
}

return sum;
}

private boolean isNumeric(String number) {
if (number == null || number.trim().isEmpty()) {
return false;
}

for (int i = 0; i < number.length(); i++) {
if (i == 0 && number.charAt(i) == '-') {
return false;
}

if (!Character.isDigit(number.charAt(i))) {
return false;
}
}

return true;
}
}
58 changes: 58 additions & 0 deletions src/test/java/CalculatorAssertTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

@DisplayName("Calculator Assert Test")
public class CalculatorAssertTest {

private Calculator calculator = new Calculator();

@Test
@DisplayName("add")
void add_test() {
int a = 1;
int b = 2;
int expected = a + b;

int actual = calculator.add(1, 2);

assertEquals(expected, actual);
}
Comment on lines +11 to +21

Choose a reason for hiding this comment

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

테스트의 이름을 정해주시려고 @DisplayName을 사용해주셨네요!
다만 테스트 이름이 너무 단순해보여요.
테스트가 하는 행동을 이름으로 표현할 수 없을까요?

Choose a reason for hiding this comment

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

테스트의 결과를 검증하려고 expected 변수를 만들어주셨네요!
다만 expected 변수를 만드는 로직과 테스트 할 대상인 calculator.add() 메서드의 내부 로직이 동일해 보여요.
테스트 하는 로직이 사칙연산이라 변경될 일이 없고 너무 간단하지만, 테스트 코드의 목적을 생각해볼 때 이러한 검증이 과연 의미가 있을까요?
그렇다면 어떠한 방법으로 검증을 해야할까요?


@Test
@DisplayName("subtract")
void subtract_test() {
int a = 1;
int b = 2;
int expected = 1 - 2;

int actual = calculator.subtract(a, b);

assertEquals(expected, actual);
}

@Test
@DisplayName("multiply")
void multiply_test() {
int a = 1;
int b = 2;
int expected = a * b;

int actual = calculator.multiply(a, b);

assertEquals(expected, actual);
}

@Test
@DisplayName("divide")
void divide_test() {
int a = 1;
int b = 2;
int expected = a / b;

int actual = calculator.divide(a, b);

assertEquals(expected, actual);
}
}
64 changes: 64 additions & 0 deletions src/test/java/CalculatorJUnit5Test.java

Choose a reason for hiding this comment

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

2단계 미션을 진행해주셨군요!
다만, 2단계 미션의 경우 JUnit5를 사용하여 테스트 코드를 작성하라고 되어 있는데, 테스트 코드에선 JUnit5를 사용하지 않은 것 같네요 😂

Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

@DisplayName("Calculator junit5 Test")
public class CalculatorJUnit5Test {

private Calculator calculator = new Calculator();

@Test
@DisplayName("add")
void add_test() {
int a = 1;
int b = 2;
int expected = a + b;

int actual = calculator.add(1, 2);

if (actual != expected) {
throw new RuntimeException("expected: <" + expected + "> but was: <" + actual + ">");
}
}

@Test
@DisplayName("subtract")
void subtract_test() {
int a = 1;
int b = 2;
int expected = 1 - 2;

int actual = calculator.subtract(a, b);

if (actual != expected) {
throw new RuntimeException("expected: <" + expected + "> but was: <" + actual + ">");
}
}

@Test
@DisplayName("multiply")
void multiply_test() {
int a = 1;
int b = 2;
int expected = a * b;

int actual = calculator.multiply(a, b);

if (actual != expected) {
throw new RuntimeException("expected: <" + expected + "> but was: <" + actual + ">");
}
}

@Test
@DisplayName("divide")
void divide_test() {
int a = 1;
int b = 2;
int expected = a / b;

int actual = calculator.divide(a, b);

if (actual != expected) {
throw new RuntimeException("expected: <" + expected + "> but was: <" + actual + ">");
}
}
}
46 changes: 46 additions & 0 deletions src/test/java/StringCalculatorAssertTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;

@DisplayName("String Calculator Assert Test")
public class StringCalculatorAssertTest {

private final StringCalculator calculator = new StringCalculator();

@Test
@DisplayName("빈 문자열을 입력하면 0을 반환한다.")
void input_empty_string() {
String input = "";

// 인자를 비교하는 다양한 방법
assertEquals(calculator.calculate(input), 0);
assertThat(calculator.calculate(input)).isZero();
assertThat(calculator.calculate(input)).isEqualTo(0);
Comment on lines +18 to +20

Choose a reason for hiding this comment

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

AssertJ와 JUnit5를 함께 사용하셨네요!
4단계 미션은 Junit5로 작성된 테스트를 AssertJ를 사용한 테스트로 바꾸는 요구사항이었어요!
JUnit5로 작성된 테스트 코드를 AssertJ로 바꿔주세요!
그리고 AssertJ로 바꾸면서 어떤 점을 느꼈는지 알려주세요!

Choose a reason for hiding this comment

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

또한 검증에 사용할 결과는 하나만 사용해도 충분할 것 같아요!

Suggested change
assertEquals(calculator.calculate(input), 0);
assertThat(calculator.calculate(input)).isZero();
assertThat(calculator.calculate(input)).isEqualTo(0);
int actual = calculator.calculate(input);
assertEquals(actual, 0);
assertThat(actual).isZero();
assertThat(actual).isEqualTo(0);

}

@Test
@DisplayName("숫자만 입력하면 숫자를 그대로 리턴한다.")
void input_only_numbers() {
String input = "123";

assertThat(calculator.calculate(input)).isEqualTo(123);
}

@Test
@DisplayName("기본 구분자가 포함된 문자열을 입력하면 숫자만 분리해 합한다.")
void input_numbers_with_basic_separator() {
String input = "1;2,3";

assertThat(calculator.calculate(input)).isEqualTo(6);
}

@Test
@DisplayName("커스텀 구분자가 포함된 문자열을 입력하면 숫자만 분리해 합한다.")
void input_numbers_with_custom_separator() {
String input = "//*\n1;2,3";

assertThat(calculator.calculate(input)).isEqualTo(6);
}
Comment on lines +39 to +45

Choose a reason for hiding this comment

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

커스텀 구분자는 * 같네요!
그런데 input에는 커스텀 구분자가 보이지 않아요 😂

Choose a reason for hiding this comment

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

추가로 음수가 들어오면 결과가 어떻게 나오는지 궁금해요!
ex) "1,-2,3"

}