Skip to content

Commit

Permalink
refactor: 불필요한 테스트 삭제 및 코드 수정
Browse files Browse the repository at this point in the history
  • Loading branch information
JHwan96 committed Feb 15, 2024
1 parent bfdb787 commit 58546f0
Show file tree
Hide file tree
Showing 8 changed files with 102 additions and 66 deletions.
2 changes: 1 addition & 1 deletion src/main/java/org/idiot/yesslave/global/jpa/JpaConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@
@Configuration
@EnableJpaAuditing
public class JpaConfig {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import lombok.RequiredArgsConstructor;
import org.idiot.yesslave.notice.domain.Notice;
import org.idiot.yesslave.notice.dto.NoticeSaveRequest;
import org.idiot.yesslave.notice.repository.NoticeRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -12,8 +13,9 @@ public class NoticeService {
private final NoticeRepository noticeRepository;

@Transactional
public Long registerNotice(Notice notice){
Notice registerNotice = noticeRepository.save(notice);
public Long registerNotice(NoticeSaveRequest noticeSaveRequest) {
System.out.println(noticeSaveRequest.getContent());
Notice registerNotice = noticeRepository.save(Notice.createNotice(noticeSaveRequest));
return registerNotice.getId();
}
}
27 changes: 14 additions & 13 deletions src/main/java/org/idiot/yesslave/notice/domain/Notice.java
Original file line number Diff line number Diff line change
@@ -1,34 +1,35 @@
package org.idiot.yesslave.notice.domain;

import lombok.Getter;
import org.hibernate.annotations.Comment;
import org.idiot.yesslave.global.jpa.AuditInformation;
import org.idiot.yesslave.notice.dto.NoticeSaveRequest;

import javax.persistence.*;

@Entity
@Getter
public class Notice extends AuditInformation {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(length=50, nullable = false)
@Column(length = 50, nullable = false)
@Comment("제목")
private String title;

@Column(columnDefinition = "TEXT", nullable = false)
@Comment("내용")
private String content;

/*
@ManyToOne(fetch=FetchType.LAZY)
@Column(name="USER_ID")
private Long userId;
*/
protected Notice() {}
private Notice(String title, String content){
this.title=title;
this.content=content;
protected Notice() {
}

private Notice(String title, String content) {
this.title = title;
this.content = content;
}

public static Notice createNotice(String title, String content){
return new Notice(title, content);
public static Notice createNotice(NoticeSaveRequest noticeSaveRequest) {
return new Notice(noticeSaveRequest.getTitle(), noticeSaveRequest.getContent());
}
}
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
package org.idiot.yesslave.notice.dto;

import lombok.Builder;
import lombok.Data;
import lombok.Getter;

import javax.validation.constraints.NotBlank;

@Data
@Getter
@Builder
public class NoticeSaveRequest {
@NotBlank
@NotBlank(message = "제목을 입력해주세요.")
private String title;
private String content;
private String content = "";

public NoticeSaveRequest() {
private NoticeSaveRequest() {
}

public NoticeSaveRequest(String title, String content) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@
import org.idiot.yesslave.notice.domain.Notice;
import org.springframework.data.jpa.repository.JpaRepository;

public interface NoticeRepository extends JpaRepository<Notice, Long> {
public interface NoticeRepository extends JpaRepository<Notice, Long> {
}
21 changes: 11 additions & 10 deletions src/main/java/org/idiot/yesslave/notice/ui/NoticeController.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,30 @@

import lombok.RequiredArgsConstructor;
import org.idiot.yesslave.notice.application.NoticeService;
import org.idiot.yesslave.notice.domain.Notice;
import org.idiot.yesslave.notice.dto.NoticeSaveRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.validation.Valid;


@RestController
@RequiredArgsConstructor
public class NoticeController {
private final NoticeService noticeService;

@PostMapping("/notice")
public ResponseEntity<Void> registerNotice(@RequestBody NoticeSaveRequest request){
Notice notice = Notice.createNotice(request.getTitle(), request.getContent());
Long response = noticeService.registerNotice(notice);
public ResponseEntity<Void> registerNotice(@RequestBody @Valid NoticeSaveRequest request) {
Long response = noticeService.registerNotice(request);

// body: ?
return ResponseEntity.created(ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(response)
.toUri())
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(response)
.toUri())
.build();
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package org.idiot.yesslave.notice.application;

import org.assertj.core.api.Assertions;
import org.assertj.core.api.SoftAssertions;
import org.idiot.yesslave.notice.domain.Notice;
import org.idiot.yesslave.notice.dto.NoticeSaveRequest;
import org.idiot.yesslave.notice.repository.NoticeRepository;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
Expand All @@ -18,32 +20,43 @@ class NoticeServiceTest {
NoticeRepository noticeRepository;

@Nested
@DisplayName(value="공지 저장")
@DisplayName("공지 저장할 때")
class noticeRegister {
final String title = "test title";
final String content = "test content";

@Test
@DisplayName("정상적으로 저장")
@DisplayName("정상적으로 저장합니다.")
void saveNotice() {
// given
Notice notice = Notice.createNotice("test title", "test content");
NoticeSaveRequest noticeSaveRequest = NoticeSaveRequest.builder()
.title(title)
.content(content)
.build();

// when
Long registerId = noticeService.registerNotice(notice);
Long registerId = noticeService.registerNotice(noticeSaveRequest);
Notice findNotice = noticeRepository.findById(registerId).get();

// then
Assertions.assertThat(findNotice).isNotNull();
Assertions.assertThat(findNotice.getTitle()).isEqualTo("test title");
Assertions.assertThat(findNotice.getContent()).isEqualTo("test content");
SoftAssertions softAssertions = new SoftAssertions();
softAssertions.assertThat(findNotice).isNotNull();
softAssertions.assertThat(findNotice.getTitle()).isEqualTo("test title");
softAssertions.assertThat(findNotice.getContent()).isEqualTo("test content");
softAssertions.assertAll();
}

@Test
@DisplayName("오류 발생(제목이 없을 경우) ")
@DisplayName("제목이 없어 오류가 발생합니다.")
void saveNoticeWithNullTitle() {
//given
Notice notice = Notice.createNotice(null, "test content");
//when
//then
NoticeSaveRequest noticeSaveRequest = NoticeSaveRequest.builder()
.content(content)
.build();
Notice notice = Notice.createNotice(noticeSaveRequest);
//expected
Assertions.assertThatThrownBy(() -> noticeRepository.save(notice)).isInstanceOf(RuntimeException.class);
}
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,8 @@

import com.fasterxml.jackson.databind.ObjectMapper;
import org.idiot.yesslave.notice.application.NoticeService;
import org.idiot.yesslave.notice.domain.Notice;
import org.idiot.yesslave.notice.dto.NoticeSaveRequest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.mockito.BDDMockito.given;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
Expand All @@ -28,7 +24,9 @@ class NoticeControllerTest {
NoticeService noticeService;
@Autowired
private MockMvc mockMvc;
final String baseUrl="/notice";
final String baseUrl = "/notice";
final String title = "test title";
final String content = "test content";

@Autowired
private WebApplicationContext ctx;
Expand All @@ -41,27 +39,48 @@ void init() {
.build();
}

@Test
@DisplayName(value="공지 생성 성공")
void createNotice() throws Exception {
mockMvc.perform(
MockMvcRequestBuilders.post(baseUrl)
.content(asJsonString(NoticeSaveRequest.builder()
.title("test title")
.content("test content")
.build()))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isCreated())
.andReturn();
given(noticeService.registerNotice(Notice.createNotice("test title", "test content"))).willReturn(1L);
@Nested
@DisplayName("공지를 생성할 때")
class noticeCreate {
@Test
@DisplayName("성공합니다")
void createNotice() throws Exception {
String requestBody = asJsonString(NoticeSaveRequest.builder()
.title(title)
.content(content)
.build());

mockMvc.perform(
MockMvcRequestBuilders.post(baseUrl)
.content(requestBody)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isCreated())
.andReturn();
}

@Test
@DisplayName("제목이 없어 실패합니다.")
void createNoticeFail() throws Exception {
String requestBody = asJsonString(NoticeSaveRequest.builder()
.content(content)
.build());

mockMvc.perform(
MockMvcRequestBuilders.post(baseUrl)
.content(requestBody)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isBadRequest());

}
}

static String asJsonString(Object object) {
try {
return new ObjectMapper().writeValueAsString(object);
} catch(Exception e){
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}

0 comments on commit 58546f0

Please sign in to comment.