SpringBoot Unit Test入门

1. Junit工作原理

使用JUnit测试,不用自己在测试类中写很多main函数测试。

单元测试返回值都为空(public void)。单元测试通过的标准(满足下面其中一个条件即可):

a)测试方法运行完没有抛出异常. 

b)测试方法抛出的异常,和“expect”定义的异常一致

当满足标准, Eclipse自动判断测试通过。

 

2 Unit Test  in SpringBoot

用如下注解修饰测试

@RunWith(SpringRunner.class)   //运行测试的类。 不写这个的情况下,会//直接用JUnit去跑。 SpringRunner是JUnit的扩展
@SpringBootTest  //可以加测试的参数,如端口
@AutoConfigureMockMvc  // 测试RestAPI的时候会用到。 封装了TestRestTemplate的相关功能

package com.github.binarywang.demo.wx.mp.controller;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.t
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是Spring Boot Unit Test的详细文档: 1. 创建测试类 在你的测试包中创建一个测试类,你可以使用JUnit或者其他测试框架。在测试类中添加注解`@RunWith(SpringRunner.class)`和`@SpringBootTest`,如下所示: ```java @RunWith(SpringRunner.class) @SpringBootTest public class YourTestClassName { // your test methods here } ``` 2. 编写测试方法 在测试类中编写测试方法,使用注解`@Test`标记这个方法为测试方法。你可以使用Spring的依赖注入和其他功能来编写你的测试方法。 ```java @Test public void yourTestMethod() { // your test logic here } ``` 3. 使用Mockito进行Mock测试 在Spring Boot Unit Test中,我们可以使用Mockito框架来进行Mock测试。Mockito可以模拟一些外部依赖,例如数据库或其他服务,使得测试更加方便和快速。下面是一个使用Mockito进行Mock测试的示例: ```java @RunWith(SpringRunner.class) @SpringBootTest public class YourTestClassName { @MockBean private YourService yourService; // mock YourService @Autowired private YourController yourController; // inject YourController @Test public void yourTestMethod() throws Exception { // mock YourService's method when(yourService.yourMethod(anyString())).thenReturn("mock result"); // call YourController's method String result = yourController.yourMethod("test"); // verify the result assertEquals("mock result", result); } } ``` 在这个例子中,我们将YourService模拟为一个MockBean,并将其注入到YourController中。然后,我们使用Mockito的when和thenReturn方法模拟YourService的方法,并调用YourController的方法测试结果。 4. 使用@WebMvcTest进行Controller测试 如果你只想测试Controller层的代码,你可以使用Spring Boot提供的@WebMvcTest注解。下面是一个使用@WebMvcTest注解进行Controller测试的示例: ```java @RunWith(SpringRunner.class) @WebMvcTest(YourController.class) public class YourTestClassName { @Autowired private MockMvc mockMvc; // inject MockMvc @Test public void yourTestMethod() throws Exception { // perform GET request MvcResult result = mockMvc.perform(get("/yourUrl")) .andExpect(status().isOk()) .andReturn(); // verify the result assertEquals("expected result", result.getResponse().getContentAsString()); } } ``` 在这个例子中,我们使用@WebMvcTest注解注入YourController并使用MockMvc执行GET请求来测试结果。 这就是Spring Boot Unit Test的详细文档。通过这些测试,你可以更加自信地开发和部署你的Spring Boot应用程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值