首页  

springboot2单元测试     所属分类 springboot 浏览量 1548
添加依赖


<dependency>
    <groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-test</artifactId>
	<scope>test</scope>
</dependency>


@RunWith(SpringRunner.class)
// @SpringBootTest(classes={AppMain.class})
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
@Transactional
public class SpringbootHelloTest {


有多个入口 需要指定一下
@SpringBootTest(classes={AppMain.class})

否则报错
java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test


@RunWith(SpringRunner.class)  

public final class SpringRunner extends SpringJUnit4ClassRunner


@RunWith(SpringJUnit4ClassRunner.class)
让测试运行于Spring测试环境,自动创建Spring应用上下文


webEnvironment = SpringBootTest.WebEnvironment.NONE  
非web环境  

@Transactional  回滚数据库事务 ,不加注解不回滚


@RestController
public class InfoController {
	
	@Autowired
	private HttpServletRequest requestField;
	
	
controller 中 注入 HttpServletRequest
需要使用 SpringBootTest.WebEnvironment.MOCK

否则报错
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'infoController': Unsatisfied dependency expressed through field 'requestField'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.servlet.http.HttpServletRequest' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.servlet.http.HttpServletRequest' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}


完整代码
https://gitee.com/dyyx/springboothello/blob/master/src/test/java/dyyx/SpringbootHelloTest.java


junit 简单实例
https://gitee.com/dyyx/springboothello/blob/master/src/test/java/dyyx/JunitHelloTest.java

上一篇     下一篇
递归与尾递归java实例

物联网云平台简介

jdk里的泛型

项目管理八大原则

springboot文件上传异常分析及解决方案

linux kill 命令