GetExampleTest.java 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package space.anyi.httpClient;
  2. import org.junit.jupiter.api.Test;
  3. import java.io.IOException;
  4. import java.net.http.HttpResponse;
  5. import static org.junit.jupiter.api.Assertions.*;
  6. /**
  7. * GET 请求示例的测试类
  8. *
  9. * <p>测试依赖本地运行的 User Management API 服务(http://localhost:8080)。</p>
  10. */
  11. class GetExampleTest {
  12. private final GetExample getExample = new GetExample();
  13. @Test
  14. void getUsers() throws IOException, InterruptedException {
  15. // 查询所有用户:状态码应为 200
  16. HttpResponse<String> response = getExample.getUsers();
  17. assertEquals(200, response.statusCode());
  18. // 响应体是标准包装结构,应包含 code 字段
  19. assertTrue(response.body().contains("\"code\""));
  20. }
  21. @Test
  22. void getUserById_notExists() throws IOException, InterruptedException {
  23. // 使用一个不存在的 id(例如 999999999),服务应返回 404
  24. HttpResponse<String> response = getExample.getUserById(999999999L);
  25. assertEquals(404, response.statusCode());
  26. }
  27. @Test
  28. void buildRequestWithQuery() {
  29. // 验证带查询参数的请求对象可以正常构建,URI 拼接正确
  30. var request = getExample.buildRequestWithQuery("alice01");
  31. assertEquals("http://localhost:8080/api/users?account=alice01",
  32. request.uri().toString());
  33. // GET 方法的 HttpRequest 不应包含请求体
  34. assertEquals(null, request.bodyPublisher().orElse(null));
  35. }
  36. }