演示环境:
SpringBoot
开发工具:IntelliJ IDEA
1.pom.xml
一般使用idea新建一个SpringBoot web项目时,一般都会自动引入此依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2 UserDAO.cs
package com.example.demo;
import org.springframework.stereotype.Repository;
@Repository
public class UserDAO {
public void AddUser()
{
System.out.print("开始AddUser");
}
}
3 UserService.cs
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserDAO userDAO;
public void AddUser()
{
this.userDAO.AddUser();
}
}
4测试类
import com.example.demo.DemoApplication;
import com.example.demo.UserService;
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;
/*
@RunWith 启动器
SpringJUnit4ClassRunner 让junit与spring 环境进行整合
@SpringBootTest(classes = DemoApplication.class) 1 当前类为Spring 的测试类 2加载SpringBoot启动类,启动SpringBoot
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes ={DemoApplication.class})
public class UserServiceText {
@Autowired
private UserService userService;
@Test
public void textAddUser()
{
this.userService.AddUser();
}
}
结果: