liujie
2026-07-29 c560a88ab429cd164d8eb6fcec42a273b898e230
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.tourguide.modules.user.service;
 
import com.tourguide.common.exception.BusinessException;
import com.tourguide.config.properties.StorageProperties;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.mock.web.MockMultipartFile;
 
import java.nio.file.Files;
import java.nio.file.Path;
 
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
 
class MiniAvatarStorageServiceTest {
    @TempDir
    Path tempDirectory;
 
    @Test
    void shouldStoreSupportedAvatarInConfiguredDirectory() throws Exception {
        StorageProperties properties = createProperties();
        MiniAvatarStorageService storageService = new MiniAvatarStorageService(properties);
        MockMultipartFile file = new MockMultipartFile(
                "file", "avatar.png", "image/png", new byte[]{1, 2, 3});
 
        String publicPath = storageService.store(file);
 
        assertThat(publicPath).startsWith("/uploads/avatars/").endsWith(".png");
        String filename = publicPath.substring(publicPath.lastIndexOf('/') + 1);
        assertThat(Files.exists(tempDirectory.resolve(filename))).isTrue();
    }
 
    @Test
    void shouldRejectUnsupportedAvatarType() {
        MiniAvatarStorageService storageService = new MiniAvatarStorageService(createProperties());
        MockMultipartFile file = new MockMultipartFile(
                "file", "avatar.txt", "text/plain", new byte[]{1, 2, 3});
 
        assertThatThrownBy(() -> storageService.store(file))
                .isInstanceOf(BusinessException.class)
                .hasMessage("头像仅支持 JPG、PNG 或 WebP 格式");
    }
 
    private StorageProperties createProperties() {
        StorageProperties properties = new StorageProperties();
        properties.setAvatarDirectory(tempDirectory.toString());
        properties.setAvatarPublicPath("/uploads/avatars");
        return properties;
    }
}