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주차 Test Code 작성 #2

Open
wants to merge 1 commit into
base: main
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
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,10 @@ private void validateAge(final int age) {

// SOPT는 한국인만 가입 가능함.
private void validateName(final String name) {
// if (!name.matches("ㅎ가-힣")) {
// throw new MemberException("한글만 가능합니다.");
// }
if (!name.matches("^[가-힣]*$")) {
Copy link
Member

Choose a reason for hiding this comment

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

정규식 이슈였군요..

throw new MemberException("한글만 가능합니다.");
}

if (name.length() > MAX_LENGTH) {
throw new MemberException("유저의 이름은 12자를 넘을 수 없습니다.");
}
Expand All @@ -74,6 +75,6 @@ private void validateNickname(final String nickname) {
}

public void updateSOPT(SOPT sopt) {
this.sopt = sopt;
this.sopt.updateSopt(sopt);
Copy link
Member

Choose a reason for hiding this comment

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

하단에 updateSopt 함수를 만들고 여기서 한번 더 실행하는 이유가 있을까요?

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,9 @@ private SOPT(Part part) {
this.generation = CURRENT_GENERATION;
this.part = part;
}

public void updateSopt(SOPT sopt) {
this.part = sopt.getPart();
this.generation = sopt.getGeneration();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ public record MemberCreateRequest(
int age,
SOPT sopt
) {
public MemberCreateRequest(String name, String nickname, int age, SOPT sopt) {
public MemberCreateRequest(String name,
String nickname, int age, SOPT sopt) {
this.name = name;
this.nickname = nickname;
this.age = age;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.example.seminar.repository;

import com.example.seminar.common.exception.MemberException;
import com.example.seminar.domain.Member;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.data.jpa.repository.JpaRepository;
Expand All @@ -8,6 +9,6 @@ public interface MemberJpaRepository extends JpaRepository<Member, Long> {

default Member findByIdOrThrow(Long id) {
return findById(id).orElseThrow(
() -> new EntityNotFoundException("존재하지 않는 회원입니다."));
() -> new MemberException("존재하지 않는 회원입니다."));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
import com.example.seminar.domain.Member;
import com.example.seminar.domain.Post;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface PostJpaRepository extends JpaRepository<Post, Long> {

List<Post> findAllByMemberId(Long memberId);
List<Post> findAllByMember(Member member);
@Query("SELECT p FROM Post p WHERE p.member.name IN :memberName")
List<Post> findAllByMemberNameIn(List<String> memberName);

}
Original file line number Diff line number Diff line change
@@ -1,15 +1,35 @@
package com.example.seminar.service.post;

import com.example.seminar.domain.Post;
import jakarta.persistence.EntityManagerFactory;
import lombok.RequiredArgsConstructor;
import org.hibernate.ScrollableResults;
import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession;
import org.hibernate.Transaction;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class PostEditor {
private final EntityManagerFactory emf;

public void editContent(Post post, String content) {
post.updateContent(content);
public void editContent(final long postId, String content) {
SessionFactory sessionFactory = emf.unwrap(SessionFactory.class);
StatelessSession session = sessionFactory.openStatelessSession();
Transaction tx = session.beginTransaction();
ScrollableResults scroll = session.createQuery("select p from Post p where p.id = :id")
.setParameter("id", postId)
.scroll();

while (scroll.next()) {
Post post = (Post) scroll.get();
System.out.println("post = " + post.getContent());
post.updateContent(content);
session.update(post);
}
tx.commit();
session.close();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public String create(PostCreateRequest request, final long memberId) {
@Transactional
public void editContent(final Long postId, final PostUpdateRequest request) {
Post post = postRetriever.findById(postId);
postEditor.editContent(post, request.content());
postEditor.editContent(postId, request.content());
}

@Transactional
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,25 +35,25 @@ void memberRegister() {
.hasMessage("회원의 나이는 0세 이상 100세 이하입니다.");
}

// @Test
// @DisplayName("한국인 사용자만 가입할 수 있다.")
// void memberWithNotKorean() {
// Assertions.assertThatThrownBy(
// () -> {
// SOPT sopt = SOPT.builder()
// .part(Part.SERVER)
// .build();
//
// Member member = Member.builder()
// .age(88)
// .name("mike")
// .sopt(sopt)
// .nickname("5hae0")
// .build();
//
// }
// ).isInstanceOf(MemberException.class)
// .hasMessage("한글만 가능합니다.")
// ;
// }
@Test
@DisplayName("한국인 사용자만 가입할 수 있다.")
void memberWithNotKorean() {
Assertions.assertThatThrownBy(
() -> {
SOPT sopt = SOPT.builder()
.part(Part.SERVER)
.build();

Member member = Member.builder()
.age(88)
.name("mike")
.sopt(sopt)
.nickname("5hae0")
.build();

}
).isInstanceOf(MemberException.class)
.hasMessage("한글만 가능합니다.")
;
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,49 @@
package com.example.seminar.domain;


import com.example.seminar.common.exception.PostException;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.ActiveProfiles;

@DataJpaTest
@ActiveProfiles("test")
public class PostTest {


@Test
@DisplayName("제목이 50자를 넘으면, 게시글을 생성할 수 없다.")
void postWithInvalidTitle() {
// given
String dummyTitle = "a".repeat(51);
// when

Assertions.assertThatThrownBy(
() -> {
Post post = Post.builder()
.title(dummyTitle)
.member(createMember("오해영"))
.content("내용")
.build();
}
).isInstanceOf(PostException.class)
.hasMessage("제목은 50자 이하여야 합니다.");

// then

}
private Member createMember(String name) {
SOPT sopt = SOPT.builder()
.part(Part.SERVER)
.build();
return Member.builder()
.age(99)
.name(name)
.sopt(sopt)
.nickname("5hae0")
.build();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.example.seminar.domain;


import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

public class SoptTest {

@Test
@DisplayName("등록되는 SOPT회원은 현재 기수여야 한다.")
void sopt() {
short CURRENT_GENERATION = (short) 34;

SOPT sopt = SOPT.builder()
.part(Part.SERVER)
.build();
// then
Assertions.assertThat(sopt.getGeneration()).isEqualTo(CURRENT_GENERATION);

}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.example.seminar.repository;

import com.example.seminar.common.exception.MemberException;
import com.example.seminar.domain.Member;
import com.example.seminar.domain.Part;
import com.example.seminar.domain.SOPT;
Expand Down Expand Up @@ -44,9 +45,13 @@ void save() {

}



@Test
@DisplayName("사용자 id를 입력하면 회원을 조회할 수 있다. 존재하지 않는 사용자는 조회할 수 없다.")
void findByIdOrThrow() {
Long NOT_REGISTERED_ID = -1L;

SOPT sopt = SOPT.builder()
.part(Part.SERVER)
.build();
Expand All @@ -64,6 +69,13 @@ void findByIdOrThrow() {
Assertions.assertThat(findMember)
.extracting("id", "age", "name", "sopt", "nickname")
.containsExactly(savedMember.getId(), 99, "오해영", sopt, "5hae0");

Assertions.assertThatThrownBy(
() -> {
memberJpaRepository.findByIdOrThrow(NOT_REGISTERED_ID);
}
).isInstanceOf(MemberException.class)
.hasMessage("존재하지 않는 회원입니다.");
}

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package com.example.seminar.service.member;

import com.example.seminar.domain.Member;
import com.example.seminar.domain.Part;
import com.example.seminar.domain.SOPT;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
Expand All @@ -18,17 +22,28 @@ public class MemberSaverTest {
@Test
@DisplayName("SOPT 회원을 등록할 수 있다.")
void register() {
StopWatch stopWatch = new StopWatch();
}

@Test
@DisplayName("새롭게 등록한 SOPT 회원은 현재 기수이다.")
void checkIsCurrentGeneration() {
// given
Member newMember = createMember("오해영");

// set up
// 생성
// when
Member registeredMember = memberRegister.register(newMember);

// 조회
// then
Assertions.assertThat(registeredMember)
.extracting("age", "name", "sopt", "nickname")
.containsExactly(99, "오해영", newMember.getSopt(), "5hae0");
}

private Member createMember(String name) {
SOPT sopt = SOPT.builder()
.part(Part.SERVER)
.build();
return Member.builder()
.age(99)
.name(name)
.sopt(sopt)
.nickname("5hae0")
.build();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.example.seminar.service.post;


import com.example.seminar.domain.Member;
import com.example.seminar.domain.Part;
import com.example.seminar.domain.Post;
import com.example.seminar.domain.SOPT;
import com.example.seminar.repository.PostJpaRepository;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;

@SpringBootTest
@ActiveProfiles("test")
public class PostEditorTest {

@Autowired
PostEditor postEditor;

@Autowired
PostSaver postSaver;

@Autowired
PostJpaRepository postJpaRepository;

@Autowired
PostRetriever postRetriever;

@Test
@DisplayName("게시글의 내용을 수정할 수 있다.")
void editContent() {
Member member = Member.builder()
.age(20)
.name("오해영")
.nickname("오해영")
.sopt(
SOPT.builder()
.part(Part.SERVER)
.build()
).build();
// given
Post post = Post.builder()
.member(member)
.title("제목")
.content("내용")
.build();
// when
Post savedPost = postJpaRepository.saveAndFlush(post);
postEditor.editContent(savedPost.getId(), "수정된 내용");
Post findPost = postRetriever.findById(savedPost.getId());
// then
Assertions.assertThat(findPost.getContent()).isEqualTo("수정된 내용");
}
}