- 引入spring-boot-starter-test ,相关jar包,如果此依赖中有排除JUnit的exclusions,需要先注销掉,引入JUnit相关依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<!--<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>-->
</dependency>
- Springboot 会在跟main同级的目录下创建test目录,包含*ApplicationTests这样的一个测试类示例:
package com.jianxin.api;
import com.jianxin.api.service.PurchaseService;
import com.jianxin.fan.entity.Product;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import tk.mybatis.spring.annotation.MapperScan;
@RunWith(SpringRunner.class)
@MapperScan("com.jianxin.fan.mapper")
@SpringBootTest
class ApiApplicationTests {
@Autowired
private PurchaseService purchaseService;
@Test
void contextLoads() {
Product product = purchaseService.getProduct(1);
// 判断产品信息是否为空
Assert.assertNotNull(product);
boolean b=purchaseService.purchase(1,1,3);
// 判断返回是否为true
Assert.assertTrue(b);
}
}
- contextLoads刚开始是一个空逻辑,其中注解@RunWith所载入类SpringRunner是spring结合JUnit的运行器,所以这里可以进行JUnit测试。@SpringBootTest是可以配置Spring boot的关于测试的相关功能。
- 加入业务逻辑代码 :
@Autowired
private PurchaseService purchaseService;
- 使用Assert.assert…()方法进行结果的判断,在该类上,右键run或debug运行,即可进行单元测试,如果涉及到数据库mapper的操作,需要使用@MapperScan(“com.jianxin.fan.mapper”),与ApiApplication(@SpringBootApplication)保持一致。
- 运行后如果有报错,说明测试没通过,如果没有报错,则测试通过。
- 有时候,本机已经启动了8080端口,这时进行测试会占用这个端口,为了克服这个问题,在Spring Boot中提供了随机端口的机制,并且可以使用REST风格进行测试。
- 使用随机端口启动测试服务,修改注解@SpringBootTest为:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
- REST风格可以使用TestRestTemplate模板,进行:
package com.jianxin.web;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
//@SpringBootTest
//可以使用随机端口启动测试服务
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class WebApplicationTests {
// REST测试模板,Springboot自动提供
@Autowired
private TestRestTemplate restTemplate;
@Test
void contextLoads() {
}
@Test
public void testPurchase(){
boolean b=this.restTemplate.getForObject("/purchase/purchase",Boolean.class,1,1,4);
}
}
- 如果遇到报错:
Test ignored.
java.lang.IllegalStateException: Found multiple @SpringBootConfiguration annotated classes [Generic bean: class [com.jianxin.WebApplication]; scope=; abstract=false; lazyInit=null; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [E:\xjst\个人\技术落地文档\学习练习项目\20200804\high-concurrent-maven-learn\hcml-web\target\classes\com\jianxin\WebApplication.class], Generic bean: class [com.jianxin.ApiApplication]; scope=; abstract=false; lazyInit=null; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [E:\xjst\个人\技术落地文档\学习练习项目\20200804\high-concurrent-maven-learn\hcml-api\target\classes\com\jianxin\ApiApplication.class]]
有可能是因为依赖的jar包(或依赖的maven其他子模块)中有springboot启动类,junit不知道加载哪个启动类,需要注解@SpringBootApplication或@SpringBootTest注解
12. 测试过程中,如果在项目中加入了spring security ,并且没有重写相关方法,需要将security注销掉,或重写security相关的验证方法,否则测试controller相关接口时,可能返回401 UNAUTHORIZED:
2020-08-07 15:30:46.065 DEBUG 10216 --- [ main] o.s.web.client.RestTemplate : HTTP GET http://localhost:50956/hcmlweb/purchase/purchase
2020-08-07 15:30:46.117 DEBUG 10216 --- [ main] o.s.web.client.RestTemplate : Accept=[application/json, application/*+json]
2020-08-07 15:30:46.199 INFO 10216 --- [o-auto-1-exec-1] o.a.c.c.C.[.[localhost].[/hcmlweb] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-08-07 15:30:46.199 INFO 10216 --- [o-auto-1-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-08-07 15:30:46.199 DEBUG 10216 --- [o-auto-1-exec-1] o.s.web.servlet.DispatcherServlet : Detected StandardServletMultipartResolver
2020-08-07 15:30:46.217 DEBUG 10216 --- [o-auto-1-exec-1] o.s.web.servlet.DispatcherServlet : enableLoggingRequestDetails='false': request parameters and headers will be masked to prevent unsafe logging of potentially sensitive data
2020-08-07 15:30:46.218 INFO 10216 --- [o-auto-1-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 19 ms
2020-08-07 15:30:46.262 DEBUG 10216 --- [o-auto-1-exec-1] o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for GET "/hcmlweb/error", parameters={}
2020-08-07 15:30:46.266 DEBUG 10216 --- [o-auto-1-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
2020-08-07 15:30:46.297 DEBUG 10216 --- [o-auto-1-exec-1] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Using 'application/json', given [application/json, application/*+json] and supported [application/json, application/*+json, application/json, application/*+json]
2020-08-07 15:30:46.298 DEBUG 10216 --- [o-auto-1-exec-1] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Writing [{timestamp=Fri Aug 07 15:30:46 CST 2020, status=401, error=Unauthorized, message=, path=/hcmlweb/pur (truncated)...]
2020-08-07 15:30:46.322 DEBUG 10216 --- [o-auto-1-exec-1] o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 401
2020-08-07 15:30:46.327 DEBUG 10216 --- [ main] o.s.web.client.RestTemplate : Response 401 UNAUTHORIZED
2020-08-07 15:30:46.328 DEBUG 10216 --- [ main] o.s.web.client.RestTemplate : Reading to [com.jianxin.web.util.Result]

本文介绍如何在Spring Boot项目中进行单元测试,包括引入依赖、创建测试类、使用JUnit进行断言、解决常见问题等。文章详细展示了如何利用Spring Boot的测试特性,如随机端口启动、REST风格测试及解决Spring Security冲突。
1406

被折叠的 条评论
为什么被折叠?



