现在springboot越来越流行,基于springboot的项目,单元测试当然必不可少了。当然基于springboot的项目集成junit做单元测试也是很简单的。
先来看看项目结构:
看看pom.xml,关键是引入spring-boot-starter-test。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.lovecto</groupId>
<artifactId>lovecto</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
</parent>
<dependencies>
<!-- 引入spring-boot-starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- 引入spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 引入spring-boot-starter-test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
应用启动类,使用@SpringBootApplication注解:
package cn.lovecto;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
添加一个service,用于测试用:
package cn.lovecto.service;
import org.springframework.stereotype.Service;
@Service
public class TestService {
/**
* 系统当前毫秒数
* @return
*/
public Long currentTimeMillis(){
return System.currentTimeMillis();
}
}
单元测试的时候,只需要在测试类上加上@RunWith注解和@SpringBootTest注解:
package cn.lovecto.service;
import org.junit.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 cn.lovecto.Application;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class TestServiceTest {
@Autowired
private TestService testService;
@Test
public void currentTimeMillis(){
System.out.println(testService.currentTimeMillis());
}
}
运行Junit Test,打印出当前的系统毫秒数。