公司一直很强调Junit的使用,前段时间写了一篇基础的junit单元测试的文章:初识Junit
链接如下:https://blog.csdn.net/u010947534/article/details/90726502
今天记录一下如何使用SpringBoot来整合Junit单元测试。
step1.创建一个maven项目:
step2:修改pom.xml,添加依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- a添加junit环境的jar包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
step3:Dao
package com.scu.Dao;
import org.springframework.stereotype.Repository;
@Repository
public class UserDaoImpl {
public void saveUser() {
System.out.println("insert into users...");
}
}
step4:Service
package com.scu.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.scu.Dao.UserDaoImpl;
@Service
public class UserServiceImpl {
@Autowired
private UserDaoImpl userDaoImpl;
public void insertUser() {
this.userDaoImpl.saveUser();
}
}
step5:使用springBoot整合Junit
1.添加applicationpackage com.scu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
2.src/test/java路径下编写测试类
package com.scu.test;
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.SpringJUnit4ClassRunner;
import com.scu.App;
import com.scu.Service.UserServiceImpl;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {App.class})
public class TestUserService {
@Autowired
private UserServiceImpl userServiceImpl;
@Test
public void testInsertUser()
{
this.userServiceImpl.insertUser();
}
}
@runwith :此注解表示启动器。
SpringJUnit4ClassRunner.class :让Junit与spring环境进行整合;
@SpringBootTest :
1.表示当前类为springBoot的测试类;
2.加载springBoot启动类,启动springBoot.