포스트

Service 계층 - File 테스트

Service 계층 - File 테스트

File mocking하기


MockMultipartFile

MockMultipartFile은 MultipartFile 인터페이스를 상속받는다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package org.springframework.mock.web;


public class MockMultipartFile implements MultipartFile {

	private final String name;

	private final String originalFilename;

	@Nullable
	private final String contentType;

	private final byte[] content;

    //...
}


테스트 코드 작성하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@Test
@DisplayName("player 중복 X")
void NotDuplicatedPlayer() throws Exception {

    //given
    PlayerRegisterDto regDto = testRegDto();
    MockMultipartFile file = testImgFile();
    ReflectionTestUtils.setField(playerService, "savePath", "/Users/giljun/trade-market/player");

    given(agentRepository.findById(1L)).willReturn(Optional.of(agent));
    given(teamRepository.findById(1L)).willReturn(Optional.of(team));
    given(positionRepository.findById(1L)).willReturn(Optional.of(position));
    given(soccerRepository.findByFifaRegNum(anyString())).willReturn(Optional.empty());

    // when
    playerService.registerPlayer(regDto, file);

    // then
    then(soccerRepository).should().findByFifaRegNum(anyString());
}

private MockMultipartFile testImgFile() throws IOException {

    Path path = Paths.get("src/test/resources/test.png");       // 해당 경로에 테스트 이미지 넣기.
    String name = "testImg.png";
    String originalFileName = "testImg.png";
    String contentType = "img/png";
    byte[] content = Files.readAllBytes(path);
    return  new MockMultipartFile(name, originalFileName, contentType, content);
}
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.