add file
Change-Id: I49ce6d06ec46cbe679e4b8771031461047c704bb
diff --git a/src/test/java/com/g9/g9backend/controller/FileControllerTest.java b/src/test/java/com/g9/g9backend/controller/FileControllerTest.java
new file mode 100644
index 0000000..a8b3d01
--- /dev/null
+++ b/src/test/java/com/g9/g9backend/controller/FileControllerTest.java
@@ -0,0 +1,82 @@
+package com.g9.g9backend.controller;
+
+import com.g9.g9backend.pojo.TorrentRecord;
+import com.g9.g9backend.service.TorrentRecordService;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.mock.web.MockMultipartFile;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Date;
+
+import static org.mockito.Mockito.verify;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+import static org.hamcrest.Matchers.containsString;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
+
+public class FileControllerTest {
+
+ private MockMvc mockMvc;
+
+ @InjectMocks
+ private FileController fileController;
+
+ @Mock
+ private TorrentRecordService torrentRecordService;
+
+ @BeforeEach
+ public void setup() {
+ MockitoAnnotations.openMocks(this);
+ mockMvc = MockMvcBuilders.standaloneSetup(fileController).build();
+ }
+
+ // 测试上传文件接口(模拟 multipart/form-data)
+ @Test
+ public void testUploadFile_success() throws Exception {
+ MockMultipartFile mockFile = new MockMultipartFile(
+ "file", // 参数名,必须为 file
+ "test.txt", // 文件名
+ "text/plain", // MIME 类型
+ "test content".getBytes(StandardCharsets.UTF_8) // 内容
+ );
+
+ mockMvc.perform(multipart("/file").file(mockFile))
+ .andExpect(status().isOk())
+ .andExpect(content().string(containsString("http://localhost:65/")));
+ }
+
+ // 测试上传 BT 文件接口
+ @Test
+ public void testUploadBTFile_success() throws Exception {
+ TorrentRecord record = new TorrentRecord();
+ record.setTorrentRecordId(1);
+ record.setTorrentUrl("test.torrent");
+ record.setInfoHash("abc123");
+ record.setUploaderUserId(1);
+ record.setUploadTime(new Date());
+
+ // 模拟 post 请求,传 json 数据
+ mockMvc.perform(post("/file/bt")
+ .contentType("application/json")
+ .content("""
+ {
+ "torrentRecordId": 1,
+ "torrentUrl": "test.torrent",
+ "infoHash": "abc123",
+ "uploaderUserId": 1,
+ "uploadTime": "2025-06-09T10:00:00"
+ }
+ """))
+ .andExpect(status().isOk());
+
+ // 验证 service 是否调用
+ verify(torrentRecordService).save(org.mockito.ArgumentMatchers.any(TorrentRecord.class));
+ }
+}