当前位置: 首页 > 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.dtcms.com/a/313695.html

相关文章:

  • 大模型能力测评(提示词请帮我把这个项目改写成为python项目)
  • 译|数据驱动智慧供应链的构成要素与关联思考
  • 死锁深度解析:原理、检测与解决之道
  • C++ <type_traits> 应用详解
  • 志邦家居PMO负责人李蓉蓉受邀为PMO大会主持人
  • 【深度学习新浪潮】谷歌新推出的AlphaEarth是款什么产品?
  • ZStack Cloud 5.3.40正式发布
  • 《测试驱动的React开发:从单元验证到集成协同的深度实践》
  • JAVA中的String类方法介绍
  • 【Bluetooth】【Transport层篇】第三章 基础的串口(UART)通信
  • 智能图书馆管理系统开发实战系列(六):Google Test单元测试实践
  • SAP 服务号传输(同环境的不同客户端SCC1,跨环境的STMS)
  • 一个网页的加载过程详解
  • lua中 list.last = last 和list[last]=value区别
  • C语言实现猜数字游戏
  • 多模态大模型综述:BLIP-2详解(第二篇)
  • 问题集000
  • 图像张量中的通道维度
  • 力扣经典算法篇-41-旋转图像(辅助数组法,原地旋转法)
  • Kubernetes中ingess以及它和nginx的关系
  • 单表查询-模糊匹配
  • CMake 命令行参数完全指南(4)
  • sqli-labs靶场less26/a
  • awk对文本进行列处理
  • 【实习总结】Qt通过Qt Linguist(语言家)实现多语言支持
  • 抖音全新推荐大模型RankMixer
  • 【AI论文】ScreenCoder:通过模块化多模态智能体推动前端自动化中的视觉到代码生成技术发展
  • 从零开始实现Qwen3(Dense架构)
  • Linux 环境下 Docker 安装与简单使用指南
  • 7.28-8.3周报