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

2단계 - 문자열 덧셈 계산기 #5924

Open
wants to merge 2 commits into
base: younghooniii
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
42 changes: 42 additions & 0 deletions src/main/java/study/step2/StringAddCalculator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package study.step2;
Copy link
Member

Choose a reason for hiding this comment

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

패키지명은 넘버링보다 기능명으로 작성하면 좋을 것 같아요.


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

public class StringAddCalculator {

public static int splitAndSum(String text) {
Copy link
Member

Choose a reason for hiding this comment

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

프로그래밍 요구사항
메소드가 너무 많은 일을 하지 않도록 분리하기 위해 노력해 본다.
를 지키기 위해 메서드를 분리해 보시면 좋을 것 같아요.

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

String[] tokens;

if (text.startsWith("//")) {
Matcher m = Pattern.compile("//(.)\n(.*)").matcher(text);
Comment on lines +15 to +16
Copy link
Member

Choose a reason for hiding this comment

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

변경되지 않는 문자열이나 패턴 객체는 상수로 선언해 이름을 부여하면 어떨까요?

if (m.find()) {
String customDelimiter = m.group(1);
tokens = m.group(2).split(Pattern.quote(customDelimiter));
} else {
throw new RuntimeException("커스텀 구분자 형식이 올바르지 않습니다.");
}
} else {
tokens = text.split(",|:");
}

int sum = 0;
for (String token : tokens) {
int number;
try {
number = Integer.parseInt(token);
} catch (NumberFormatException e) {
throw new RuntimeException("숫자가 아닌 값이 포함되어 있습니다: " + token);
}
if (number < 0) {
throw new RuntimeException("음수는 허용되지 않습니다: " + number);
}
Comment on lines +30 to +37
Copy link
Member

Choose a reason for hiding this comment

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

문자열을 분리하기 전에 유효성을 먼저 검증하면 어떨까요?

sum += number;
}
return sum;
}
}
62 changes: 62 additions & 0 deletions src/test/java/study/step1/SetTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package study.step1;

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

import java.util.HashSet;
import java.util.Set;

import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

public class SetTest {
Copy link
Member

Choose a reason for hiding this comment

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

피드백이 반영되지 않은 커밋이 그대로 남아 있네요.
온라인 코드 요청 3단계 가이드 문서를 참고해서 rebase 후 피드백 반영도 함께 해주시면 좋을 것 같아요


private Set<Integer> numbers;

@BeforeEach
void setUp() {
numbers = new HashSet<>();
numbers.add(1);
numbers.add(1);
numbers.add(2);
numbers.add(3);
}

@Nested
class requirements1 {
@Test
void setSize() {
assertEquals(3, numbers.size());
}
}

@Nested
class requirements2 {
@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
void parameterizedValueScoreTest(int number) {
assertThat(numbers.contains(number)).isTrue();
}
}

@Nested
class requirements3 {
@ParameterizedTest
@CsvSource({
"1, true",
"2, true",
"3, true",
"4, false",
"5, false"
})
void parameterizedCsvSourceTest(int number, boolean expected) {
assertThat(numbers.contains(number)).isEqualTo(expected);
}
}
}
52 changes: 52 additions & 0 deletions src/test/java/study/step1/StringTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package study.step1;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

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

public class StringTest {

@Nested
class requirements1 {
@Test
void splitString1() {
String input = "1,2";
String[] result = input.split(",");
assertThat(result).containsExactly("1", "2");
}

@Test
void splitString2() {
String input = "1";
String[] result = input.split(",");
assertThat(result).containsExactly("1");
}
}

@Nested
class requirements2 {
@Test
void substringString() {
String input = "(1,2)";
String result = input.substring(1, input.length() - 1);
assertThat(result).isEqualTo("1,2");
}
}

@Nested
class requirements3 {
@Test
@DisplayName("문자열 \"abc\"에서 범위를 벗어난 인덱스의 문자를 요청하면 예외가 발생한다")
void charAtString() {
String input = "abc";
int index = 10;
assertThrows(StringIndexOutOfBoundsException.class, () -> {
input.charAt(index);
}, "인덱스 " + index + " 은 문자열의 길이를 벗어나므로 예외가 발생해야 한다");
}
}

}
47 changes: 47 additions & 0 deletions src/test/java/study/step2/StringAddCalculatorTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package study.step2;

import org.junit.jupiter.api.Test;

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

public class StringAddCalculatorTest {
@Test
public void splitAndSum_null_또는_빈문자() {
int result = StringAddCalculator.splitAndSum(null);
assertThat(result).isEqualTo(0);

result = StringAddCalculator.splitAndSum("");
assertThat(result).isEqualTo(0);
}

@Test
public void splitAndSum_숫자하나() throws Exception {
int result = StringAddCalculator.splitAndSum("1");
assertThat(result).isEqualTo(1);
}

@Test
public void splitAndSum_쉼표구분자() throws Exception {
int result = StringAddCalculator.splitAndSum("1,2");
assertThat(result).isEqualTo(3);
}

@Test
public void splitAndSum_쉼표_또는_콜론_구분자() throws Exception {
int result = StringAddCalculator.splitAndSum("1,2:3");
assertThat(result).isEqualTo(6);
}

@Test
public void splitAndSum_custom_구분자() throws Exception {
int result = StringAddCalculator.splitAndSum("//;\n1;2;3");
assertThat(result).isEqualTo(6);
}

@Test
public void splitAndSum_negative() throws Exception {
assertThatThrownBy(() -> StringAddCalculator.splitAndSum("-1,2,3"))
.isInstanceOf(RuntimeException.class);
}
}