spring boot mock单元测试
时间: 2023-07-13 11:07:16 浏览: 105
在Spring Boot中进行mock单元测试的步骤如下:
1. 添加Mockito和JUnit的依赖:
```xml
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.6.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.6.2</version>
<scope>test</scope>
</dependency>
```
2. 创建测试类并添加注解:
```java
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
public class MyServiceTest {
@Mock
private MyRepository myRepository;
@Test
public void testMyService() {
//写测试代码
}
}
```
3. 创建Mock对象:
```java
@Mock
private MyRepository myRepository;
```
4. 编写测试代码:
```java
import static org.mockito.Mockito.when;
public class MyServiceTest {
@Mock
private MyRepository myRepository;
@Test
public void testMyService() {
when(myRepository.findByName("John")).thenReturn(new MyEntity("John", 30));
MyService myService = new MyService(myRepository);
MyEntity result = myService.getByName("John");
assertEquals("John", result.getName());
assertEquals(30, result.getAge());
}
}
```
在这个例子中,我们使用Mockito创建了一个MyRepository的Mock对象,并且在测试代码中定义了当调用findByName("John")方法时返回一个MyEntity对象。然后我们使用这个Mock对象创建了一个MyService对象并调用getByName("John")方法,并验证返回值与预期值相等。
这就是使用Mockito进行Spring Boot mock单元测试的基本步骤。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)