当前位置: 移动技术网 > IT编程>开发语言>Java > 使用@SpringBootTest注解进行单元测试

使用@SpringBootTest注解进行单元测试

2020年09月17日  | 移动技术网IT编程  | 我要评论
概述@springboottest注解是springboot自1.4.0版本开始引入的一个用于测试的注解。基本用法如下:1. 添加maven依赖<properties> <proj

概述

@springboottest注解是springboot自1.4.0版本开始引入的一个用于测试的注解。基本用法如下:

1. 添加maven依赖

<properties>
  <project.build.sourceencoding>utf-8</project.build.sourceencoding>
 </properties>

 <parent>
  <groupid>org.springframework.boot</groupid>
  <artifactid>spring-boot-starter-parent</artifactid>
  <version>1.5.6.release</version>
 </parent>

 <dependencies>
  <dependency>
   <groupid>org.springframework.boot</groupid>
   <artifactid>spring-boot-starter-web</artifactid>
  </dependency>
  <dependency>
   <groupid>org.springframework.boot</groupid>
   <artifactid>spring-boot-starter-test</artifactid>
  </dependency>
 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-maven-plugin</artifactid>
   </plugin>
  </plugins>
 </build>

2. 编写启动入口类

@springbootapplication
public class startupapplication {
 public static void main(string[] args) {
  springapplication.run(startupapplication.class, args);
 }
}

3. 编写controller类

@restcontroller
public class hellocontroller {

 @requestmapping("/")
 public string index() {
  return "hello spring boot,index!";
 }

 @requestmapping(value = "/test", method = requestmethod.get)
 public string test() {
  return "spring boot test demo!";
 }
}

4. 编写测试类

@runwith(springrunner.class)
@springboottest(classes = startupapplication.class, webenvironment = springboottest.webenvironment.random_port)
public class hellocontrollertest {

 /**
  * @localserverport 提供了 @value("${local.server.port}") 的代替
  */
 @localserverport
 private int port;

 private url base;

 @autowired
 private testresttemplate resttemplate;

 @before
 public void setup() throws exception {
  string url = string.format("http://localhost:%d/", port);
  system.out.println(string.format("port is : [%d]", port));
  this.base = new url(url);
 }

 /**
  * 向"/test"地址发送请求,并打印返回结果
  * @throws exception
  */
 @test
 public void test1() throws exception {

  responseentity<string> response = this.resttemplate.getforentity(
    this.base.tostring() + "/test", string.class, "");
  system.out.println(string.format("测试结果为:%s", response.getbody()));
 }

其中,classes属性指定启动类,springboottest.webenvironment.random_port经常和测试类中@localserverport一起在注入属性时使用。会随机生成一个端口号。

总结

我们发现,随着spring boot 版本的提升,单元测试变得更简单了。

到此这篇关于使用@springboottest注解进行单元测试的文章就介绍到这了,更多相关@springboottest 单元测试内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网