1、pom.xml中引入junit依赖,就是他的starter
2、创建他的service通过@service注解交给Spring
3、编写对应的测试类
进行SpringBoot整合Junit单元测试时,我们需要先将junit的start的依赖引入
1、在pom.xml中引入Junit环境依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
2、 创建我们需要的service:
通过@service交给
package com.cmj.service;
import org.springframework.stereotype.Service;
@Service
public class UserService {
public void add() {
System.out.println("add");
}
}
3、设置我们的测试类
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 com.cmj.CmjApplication;
import com.cmj.dao.TeacherMapper;
import com.cmj.entity.Teacher;
import com.cmj.service.UserService;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = CmjApplication.class)
public class CmjTest {
@Autowired
private UserService userService;
@Test
public void test() {
userService.add();
}
}
所调用的main方法是写在我们对应的CmjApplication.class中
package com.cmj;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class CmjApplication {
public static void main(String[] args) {
SpringApplication.run(CmjApplication.class,args);
}
}
测试结果: