一、首先添加相关依赖的jar包
<!-- 测试依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
二、创建一个Service类进行测试
package com.example.serviceimpl;
import com.example.springbootdemo.JunitTest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
/**
* Author: Chenly
* Date: 2021-03-30 11:57
* Description:
*/
@Service
public class JunitService {
private static Logger log = LoggerFactory.getLogger(JunitTest.class);
public void test(){
log.info("进入到JunitService中的test方法中");
}
}
三、创建一个测试类
- 通常我们的单元测试类是创建在src/test/路径下,在测试类上面添加@RunWith,@SpringBootTest注解,然后创建一个测试方法并添加@Test注解
package com.example.springbootdemo;
import com.example.serviceimpl.JunitService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Author: Chenly
* Date: 2021-03-30 09:41
* Description: Junit测试
*/
@RunWith(SpringRunner.class)
@SpringBootTest()
public class JunitTest {
private static Logger log = LoggerFactory.getLogger(JunitTest.class);
@Autowired
private JunitService junitService;
@Test
public void test(){
log.info("这里是Junit测试");
junitService.test();
}
}
四、选中启动类进行测试