1.通学习前面的文章,创建项目,项目名自定义。
2.引入starter-test起步依赖
<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>
<scope>test</scope>
</dependency>
</dependencies>
将上面的依赖引入pom.xml文件即可
3.编写一个Service类
在main/java/com.example.springboottest右击新建java class
在框中输入UserService 然后回车
在UserService类中,输入 代码做测试
package com.example.springboottest;
import org.springframework.stereotype.Service;
import java.util.Date;
@Service
public class UserService {
public void printDate(){
System.out.println(new Date());
}
}
4.编写测试类
方法一
我们在test/java/com.example新建一个test包
在右击test包,选中new——》在选中java class——》新建一个userServiceTest类
在该类输入如下代码
package com.example.test;
import com.example.springboottest.SpringBootTestApplication;
import com.example.springboottest.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest(classes = SpringBootTestApplication.class)//不同包名的情况下需要写入引导类
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void printDate(){
userService.printDate();
}
}
打印输出结果为:
Sat Jul 30 21:19:42 CST 2022
方法二
在test/java/目录下直接右击——》右击New——》选中package
输入和main/java路径下一样的包名,也就是UserService同包名
在包下新建java calss 文件,文件名为UserServiceTest
这个test/java/com.example.springboottest包下的UserServiceTest文件中输入如下代码
package com.example.springboottest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest//不同包名的情况下需要写入引导类
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void printDate(){
userService.printDate();
}
}
运行结果为:
Sat Jul 30 21:25:23 CST 2022