小工具知识网

当前位置: 首页 > 行业知识 > Spring boot 单元测试类

行业知识

Spring boot 单元测试类

2026-12-05 07:06:43 来源:互联网转载

在Spring Boot中,我们可以使用Spring Boot Test框架来进行单元测试。这是一个非常强大的工具,可以帮助我们模拟Spring环境,进行各种测试,如集成测试、容器测试等。

()

以下是一些Spring Boot 单元测试的示例。

基本的Spring Boot测试

()
@RunWith(SpringRunner.class)@SpringBootTestpublic class SampleControllerTest {     @Autowired    private WebApplicationContext context;     private MockMvc mockMvc;     @Before    public void setup() {        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();    }     @Test    public void testHello() throws Exception {        mockMvc.perform(get("/hello")).andExpect(status().isOk())                .andExpect(content().string(equalTo("Hello, World!")));    }}

在这个例子中,我们使用@SpringBootTest注解来启动完整的Spring上下文,并使用MockMvc来模拟Web请求。

使用@WebMvcTest进行Spring MVC测试

@RunWith(SpringRunner.class)@WebMvcTest(SampleController.class)public class SampleControllerWebMvcTest {     @Autowired    private MockMvc mockMvc;     @Test    public void testHello() throws Exception {        mockMvc.perform(get("/hello")).andExpect(status().isOk())                .andExpect(content().string(equalTo("Hello, World!")));    }}

在这个例子中,我们使用@WebMvcTest注解来启动Spring MVC的上下文,并只扫描和加载SampleController.class相关的beans。

使用@DataJpaTest进行Spring Data JPA测试

@RunWith(SpringRunner.class)@DataJpaTestpublic class SampleRepositoryTest {     @Autowired    private TestEntityManager entityManager;     @Autowired    private SampleRepository repository;     @Test    public void testFindByName() {        entityManager.persist(new SampleEntity("Sample Name"));        Optional foundSampleEntity = repository.findByName("Sample Name");        assertTrue(foundSampleEntity.isPresent());    }}

在这个例子中,我们使用@DataJpaTest注解来启动Spring Data JPA的上下文,并模拟JPA的操作。

使用@RestClientTest进行Rest客户端测试

@RunWith(SpringRunner.class)@RestClientTest(SampleRestClient.class)public class SampleRestClientTest {     @Autowired    private SampleRestClient restClient;     @Test    public void testGetSampleData() {        String response = "{\"name\":\"Sample Name\"}";        MockRestServiceServer server = MockRestServiceServer.create(restClient);        server.expect(requestTo("/sample/data")).andRespond(withSuccess(response, MediaType.APPLICATION_JSON));        SampleData sampleData = restClient.getSampleData();        assertEquals("Sample Name", sampleData.getName());        server.verify();    }}

在这个例子中,我们使用@RestClientTest注解来模拟Rest客户端的行为,并模拟Rest服务的响应。

上一篇:Java中数组分析

下一篇:误删APP不用愁,恢复指南帮你轻松找回应用!