当前位置: 首页 > news >正文

SpringBoot AI自动化测试实战案例

基于Spring Boot的AI自动化测试实例

以下是一些基于Spring Boot的AI自动化测试实例,涵盖不同场景和技术栈的示例:

测试REST API

使用@SpringBootTestTestRestTemplate测试RESTful接口:

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class UserControllerTest {@Autowiredprivate TestRestTemplate restTemplate;@Testvoid getUserById() {ResponseEntity<User> response = restTemplate.getForEntity("/users/1", User.class);assertEquals(HttpStatus.OK, response.getStatusCode());assertEquals("John", response.getBody().getName());}
}

数据库测试

使用@DataJpaTest测试JPA仓库:

@DataJpaTest
class UserRepositoryTest {@Autowiredprivate UserRepository userRepository;@Testvoid findByEmail() {User user = new User("test@example.com", "password");userRepository.save(user);Optional<User> found = userRepository.findByEmail("test@example.com");assertTrue(found.isPresent());}
}

模拟测试

使用Mockito模拟服务层:

@WebMvcTest(UserController.class)
class UserControllerMockTest {@Autowiredprivate MockMvc mockMvc;@MockBeanprivate UserService userService;@Testvoid getUserById() throws Exception {when(userService.getUserById(1L)).thenReturn(new User(1L, "John"));mockMvc.perform(get("/users/1")).andExpect(status().isOk()).andExpect(jsonPath("$.name").value("John"));}
}

集成测试

测试多组件集成:

@SpringBootTest
@AutoConfigureMockMvc
class OrderIntegrationTest {@Autowiredprivate MockMvc mockMvc;@Testvoid createOrder() throws Exception {mockMvc.perform(post("/orders").contentType(MediaType.APPLICATION_JSON).content("{\"productId\":1,\"quantity\":2}")).andExpect(status().isCreated());}
}

测试配置

使用测试专用配置:

@TestConfiguration
class TestConfig {@Bean@Primarypublic PaymentService mockPaymentService() {return mock(PaymentService.class);}
}@SpringBootTest
@Import(TestConfig.class)
class PaymentServiceTest {@Autowiredprivate PaymentService paymentService;@Testvoid processPayment() {when(paymentService.process(any())).thenReturn(true);assertTrue(paymentService.process(new Payment()));}
}

测试安全端点

测试受保护的API:

@SpringBootTest
@AutoConfigureMockMvc
class SecureControllerTest {@Autowiredprivate MockMvc mockMvc;@Test@WithMockUser(username="admin", roles={"ADMIN"})void adminEndpoint() throws Exception {mockMvc.perform(get("/admin")).andExpect(status().isOk());}
}

测试异常处理

验证异常响应:

@WebMvcTest
class ExceptionHandlerTest {@Autowiredprivate MockMvc mockMvc;@Testvoid notFound() throws Exception {mockMvc.perform(get("/not-exist")).andExpect(status().isNotFound()).andExpect(jsonPath("$.message").value("Not Found"));}
}

测试定时任务

验证定时任务执行:

@SpringBootTest
class ScheduledTaskTest {@SpyBeanprivate ReportGenerator reportGenerator;@Testvoid testScheduledTask() throws InterruptedException {Thread.sleep(5000); // 等待定时任务触发verify(reportGenerator, atLeastOnce()).generate();}
}

测试消息队列

验证消息发送:

@SpringBootTest
@EmbeddedKafka
class KafkaProducerTest {@Autowiredprivate KafkaTemplate<String, String> kafkaTemplate;@Testvoid sendMessage() throws Exception {kafkaTemplate.send("test-topic", "test-message");// 使用@KafkaListener在测试消费者中验证}
}

性能测试

使用JUnit 5进行性能测试:

@SpringBootTest
@ActiveProfiles("test")
class PerformanceTest {@Autowiredprivate OrderService orderService;@RepeatedTest(10)@Timeout(1)void processOrderPerformance() {orderService.process(new Order());}
}

测试GraphQL API

测试GraphQL端点:

@SpringBootTest
@AutoConfigureMockMvc
class GraphQLTest {@Autowiredprivate MockMvc mockMvc;@Testvoid queryUser() throws Exception {String query = "{ user(id:1) { name } }";mockMvc.perform(post("/graphql").contentType("application/json").content("{\"query\":\"" + query + "\"}")).andExpect(status().isOk()).andExpect(jsonPath("$.data.user.name").exists());}
}

测试WebSocket

验证WebSocket通信:

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class WebSocketTest {@LocalServerPortprivate int port;@Testvoid chatEndpoint() throws Exception {WebSocketClient client = new StandardWebSocketClient();WebSocketSession session = client.doHandshake(new TextWebSocketHandler() {},"ws://localhost:" + port + "/chat").get();assertTrue(session.isOpen());session.close();}
}

测试文件上传

验证文件上传功能:

@SpringBootTest
@AutoConfigureMockMvc
class FileUploadTest {@Autowiredprivate MockMvc mockMvc;@Testvoid uploadFile() throws Exception {MockMultipartFile file = new MockMultipartFile("file", "test.txt", "text/plain", "content".getBytes());mockMvc.perform(multipart("/upload").file(file)).andExpect(status().isOk());}
}

测试缓存

验证缓存行为:

@SpringBootTest
@CacheConfig(cacheNames = "products")
class ProductServiceTest {@Autowiredprivate ProductService productService;@MockBeanprivate ProductRepository productRepository;@Testvoid cacheProduct() {when(productRepository.findById(1L)).thenReturn(Optional.of(new Product(1L, "Phone")));productService.getProduct(1L);productService.getProduct(1L); // 第二次调用应使用缓存verify(productRepository, times(1)).findById(1L);}
}

测试OAuth2

验证OAuth2保护端点:

@SpringBootTest
@AutoConfigureMockMvc
class OAuth2Test {@Autowiredprivate MockMvc mockMvc;@Test@WithOAuth2Tokenvoid securedEndpoint() throws Exception {mockMvc.perform(get("/api/secure")).andExpect(status().isOk());}
}

测试Actuator端点

验证健康检查端点:

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class ActuatorTest {@Autowiredprivate TestRestTemplate restTemplate;@Testvoid healthEndpoint() {ResponseEntity<String> response = restTemplate.getForEntity("/actuator/health", String.class);assertEquals(HttpStatus.OK, response.getStatusCode());assertTrue(response.getBody().contains("\"status\":\"UP\""));}
}

测试多数据源

验证多数据源配置:

@SpringBootTest
@Transactional("secondaryTransactionManager")
class MultiDataSourceTest {@Autowired@Qualifier("secondaryEntityManager")private EntityManager entityManager;@Testvoid saveToSecondary() {LogEntry entry = new LogEntry("test");entityManager.persist(entry);assertNotNull(entry.getId());}
}

测试验证逻辑

验证Bean Validation:

@SpringBootTest
class ValidationTest {@Autowiredprivate Validator validator;@Testvoid invalidUser() {User user = new User("", "short");Set<ConstraintViolation<User>> violations = validator.validate(user);assertEquals(2, violations.size());}
}

测试国际化

验证多语言支持:

@SpringBootTest
@AutoConfigureMockMvc
class I18nTest {@Autowiredprivate MockMvc mockMvc;@Testvoid frenchMessage() throws Exception {mockMvc.perform(get("/greeting").header("Accept-Language", "fr")).andExpect(content().string(containsString("Bonjour")));}
}

测试重试机制

验证Spring Retry:

@SpringBootTest
class RetryServiceTest {@Autowiredprivate RetryService retryService;@MockBeanprivate ExternalService externalService;@Testvoid retryOnFailure() {when(externalService.call()).thenThrow(new RuntimeException()).thenReturn("success");assertEquals("success", retryService.doSomething());verify(externalService, times(2)).call();}
}

测试异步方法

验证异步执行:

@SpringBootTest
class AsyncServiceTest {@Autowiredprivate AsyncService asyncService;@Testvoid asyncTask() throws Exception {CompletableFuture<String> future = asyncService.asyncMethod();assertEquals("done", future.get(2, TimeUnit.SECONDS));}
}

测试自定义注解

验证自定义注解行为:

@SpringBootTest
@AutoConfigureMockMvc
class LoggableTest {@Autowiredprivate MockMvc mockMvc;@MockBeanprivate LoggingAspect loggingAspect;@Testvoid loggableAnnotation() throws Exception {mockMvc.perform(get("/loggable"));verify(loggingAspect).logMethod(any());}
}

测试响应式端点

验证WebFlux端点:

@SpringBootTest
@AutoConfigureWebTestClient
class ReactiveControllerTest {@Autowiredprivate WebTestClient webTestClient;@Testvoid fluxEndpoint() {webTestClient.get().uri("/flux").exchange().expectStatus().isOk().expectBodyList(Integer.class).hasSize(3);}
}

测试事务回滚

验证事务行为:

@SpringBootTest
@Transactional
class TransactionTest {@Autowiredprivate UserRepository userRepository;@Test
http://www.lryc.cn/news/609328.html

相关文章:

  • GitCode疑难问题诊疗
  • Linux命令基础(下)
  • 1.内核模块
  • 14.Redis 哨兵 Sentinel
  • 2. 字符设备驱动
  • IO流-对象流
  • 克罗均线策略思路
  • `npm error code CERT_HAS_EXPIRED‘ 问题
  • Java Stream API 编程实战
  • 2025年渗透测试面试题总结-2025年HW(护网面试) 77-1(题目+回答)
  • 《测试驱动的React开发:从单元验证到集成协同的深度实践》
  • 【2025ICCV-目标检测方向】WaveMamba:用于 RGB-红外目标检测的小波驱动曼巴融合
  • 百度招黑产溯源安全工程师
  • SQL注入SQLi-LABS 靶场less31-38详细通关攻略
  • Maxscript在选择的可编辑多边形每个面上绘制一个内部圆形
  • 【高等数学】第七章 微分方程——第十节 常系数线性微分方程组解法举例
  • [硬件电路-140]:模拟电路 - 信号处理电路 - 锁定放大器概述、工作原理、常见芯片、管脚定义
  • 类与对象(中),咕咕咕
  • Zama的使命
  • 零确认双花攻击
  • 8月3日星期日今日早报简报微语报早读
  • 《从原理到实践:MySQL索引优化与SQL性能调优全解析》
  • 【Redis学习路|第一篇】初步认识Redis
  • C的运算符与表达式
  • BP神经网络:当线性模型已到尽头,如何用“人造大脑”挖掘非线性预测规律?
  • 26李林880高数第二章 一元函数微分学及其应用
  • Kafka 是什么?
  • SpringBoot项目数据脱敏(自定义注解)
  • C语言基础03——数组——习题
  • GPIO交换矩阵和IO_MUX