Spring boot 单元测试类

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

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

基本的Spring Boot测试

@RunWith(SpringRunner.class)
@SpringBootTest
public 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)
@DataJpaTest
public class SampleRepositoryTest {
 
    @Autowired
    private TestEntityManager entityManager;
 
    @Autowired
    private SampleRepository repository;
 
    @Test
    public void testFindByName() {
        entityManager.persist(new SampleEntity("Sample Name"));
        Optional<SampleEntity> 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服务的响应。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值