Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

step1. test 통과 #837

Open
wants to merge 1 commit into
base: lim-devv
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
45 changes: 45 additions & 0 deletions src/main/java/stringcalculator/StringCalculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package stringcalculator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringCalculator {
Copy link

Choose a reason for hiding this comment

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

현재 StringCalculator 가 매우 많은 역할을 하고 있는 것으로 보여져요. 😢
클래스를 분리해서 각각 객체간의 역함을 위임하여 객체간의 협력으로 문제를 풀어보면 어떨까요?


public StringCalculator() {
}
Comment on lines +8 to +9
Copy link

Choose a reason for hiding this comment

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

기본생성자를 추가해주신 의도가 있을까요? 🤔


public int add(String text) {
if (text == null || text.length() == 0) {
return 0;
}

Matcher matcher = Pattern.compile("//(.)\n(.*)").matcher(text);
Copy link

Choose a reason for hiding this comment

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

정규식을 다루는 Pattern 은 생성비용이 매우 비싸요. 😢
매번 생성하는 것보다 재활용을 해보는 것은 어떨까요?

String separator = ",|:"; // 기본 구분자
Copy link

Choose a reason for hiding this comment

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

주석으로 표현하기 보다는 상수로 의미를 부여해보면 어떨까요?


// 구분자 사이에 값이 있으면 separator 을 구분자로 변경
if (matcher.matches()) {
separator = Pattern.quote(matcher.group(1));
text = matcher.group(2);
Comment on lines +21 to +22
Copy link

Choose a reason for hiding this comment

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

1,2 또한 비즈니스적으로 의미가 있는 것으로 보여요.
여기도 의미를 부여해보면 어떨까요?

}

String[] split = split(text, separator);
int init = 0;

try {
for (String s : split) {
int i = Integer.parseInt(s);
if (i < 0) {
throw new RuntimeException("문자열 계산기에 음수를 전달할 수 없다.");
}
init += i;
}
return init;
} catch (Exception e) {
throw new RuntimeException("문자열 계산기에 숫자 이외의 값을 전달 할 수 없다.");
}
}

private String[] split(String text, String separator) {
return text.split(separator);
}
}
64 changes: 64 additions & 0 deletions src/test/java/stringcalculator/StringCalculatorTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package stringcalculator;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullAndEmptySource;
import org.junit.jupiter.params.provider.ValueSource;

public class StringCalculatorTest {

private StringCalculator calculator;

@BeforeEach
void setUp() {
calculator = new StringCalculator();
}

@DisplayName(value = "빈 문자열 또는 null 값을 입력할 경우 0을 반환해야 한다.")
@ParameterizedTest
@NullAndEmptySource
void emptyOrNull(final String text) {
assertThat(calculator.add(text)).isZero();
}

@DisplayName(value = "숫자 하나를 문자열로 입력할 경우 해당 숫자를 반환한다.")
@ParameterizedTest
@ValueSource(strings = {"1"})
void oneNumber(final String text) {
assertThat(calculator.add(text)).isSameAs(Integer.parseInt(text));
Copy link

Choose a reason for hiding this comment

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

저는 테스트코드에서 검증할때 하드코딩을 선호해요.
아래 링크도 참고해보시면 좋을 것 같아요.
https://jojoldu.tistory.com/615

}

@DisplayName(value = "숫자 두개를 쉼표(,) 구분자로 입력할 경우 두 숫자의 합을 반환한다.")
@ParameterizedTest
@ValueSource(strings = {"1,2"})
void twoNumbers(final String text) {
assertThat(calculator.add(text)).isSameAs(3);
}

@DisplayName(value = "구분자를 쉼표(,) 이외에 콜론(:)을 사용할 수 있다.")
@ParameterizedTest
@ValueSource(strings = {"1,2:3"})
void colons(final String text) {
assertThat(calculator.add(text)).isSameAs(6);
}

@DisplayName(value = "//와 \\n 문자 사이에 커스텀 구분자를 지정할 수 있다.")
@ParameterizedTest
@ValueSource(strings = {"//;\n1;2;3"})
void customDelimiter(final String text) {
assertThat(calculator.add(text)).isSameAs(6);
}

@DisplayName(value = "문자열 계산기에 음수를 전달하는 경우 RuntimeException 예외 처리를 한다.")
@Test
void negative() {
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> calculator.add("-1"));
}

}