package com.gn.mvc.service;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.gn.mvc.entity.Board;
import lombok.RequiredArgsConstructor;
@SpringBootTest
class BoardServiceTest {
@Autowired
private BoardService service;
@Test
void selectBoardOne_success() {
// 1. 예상 데이터
Long id = 4L;
Board expected = Board.builder().boardTitle("제목1").build();
// 2. 실제 데이터
Board real = service.selectBoardOne(id);
// 3. 비교 및 검증
assertEquals(expected.getBoardTitle(), real.getBoardTitle());
}
// 실패 테스트
// 존재하지 않는 PK기준으로 조회 요청
@Test
void selectBoardOne_fail() {
// 1. 실패 예상 PK 데이터
Long id = 100000000000000L;
// 2. 실패 예상 PK를 사용한 데이터 조회
Board expected = service.selectBoardOne(id);
// 3. 비교 및 검증
assertEquals(expected, null);
}
}
1) application.properties에 게시글 첨부 파일이 저장될 위치 추가
- application.properties 를 사용하면 유동성이 높다.(=유동성이 높은 파일이다. 유지 보수 관리 편하다.)
ffupload.location=C:/upload/
2) MvcApplication.java에 implements WebMvcConfigurer 한다.
- WebMvcConfigurer -> 바깥쪽에 있는 파일을 가져올 때 사용하는 스프링이 가지고 있는 Servlet이다.
3) 파일 정보를 담을 수 있는 AttachDto 생성.
4) service 아래에 AttachService 생성
5) AttachService에 MultipartFile 데이터를 받아서 컴퓨터에 파일을 저장하고 메타 데이터가 담긴 Dto를 리턴하는 메소드 생성
@Service
@RequiredArgsConstructor
public class AttachService {
private final BoardRepository boardRepository;
private final AttachRepository attachRepository;
@Value("${ffupload.location}")
private String fileDir;
public AttachDto uploadFile(MultipartFile file) {
AttachDto dto = new AttachDto();
try {
// 1. 정상 파일 여부 확인(없는 파일인지 아닌지)
if(file == null || file.isEmpty()) {
throw new Exception("존재하지 않는 파일입니다.");
}
// 2. 파일 최대 용량 체크
// Spring 허용 파일 최대 용량 1MB(1048576byte)
// byte -> KB -> MB
long fileSize = file.getSize();
if(fileSize >= 1048576) {
throw new Exception("허용 용량을 초과하는 파일입니다.");
}
// 3. 파일 최초 이름 읽어오기
String oriName = file.getOriginalFilename();
dto.setOri_name(oriName);
// 4. 파일 확장자 자르기
String fileExt = oriName.substring(oriName.lastIndexOf("."));
// String fileExt = oriName.substring(oriName.lastIndexOf("."), oriName.length());
// 5. 파일 명칭 바꾸기
UUID uuid = UUID.randomUUID();
// 6. uuid의 8자리마다 반복되는 하이픈 제거
String uniqueName = uuid.toString().replaceAll("-", "");
// 7. 새로운 파일명 생성
String newName = uniqueName + fileExt;
dto.setNew_name(newName);
// 8. 파일 저장 경로 설정. C:/upload/board/newName
String downDir = fileDir + "board/" + newName;
dto.setAttach_path(downDir);
// 9. 파일 껍데기 생성
File saveFile = new File(downDir);
// 10. 경로 존재 유무 확인
if(saveFile.exists() == false) {
saveFile.mkdirs();
}
// 11. 껍데기에 파일 정보 복제(file이 알맹이?)
file.transferTo(saveFile);
} catch (Exception e) {
// throw를 만나면 dto가 null로 초기화 된다.
dto = null;
e.printStackTrace();
}
return dto;
}
}
service selectAttachList
-> board의 repository를 통해 board객체 반환받음
-> specification을 만들어서 criteriaBuilder.equal 사용해서 board 반환하는 메소드 만듦.
-> service에서 위의 specification 메소드를 불러와서 사용
-> attachRepository를 통해 findAll(spec을 매개변수로)