springboot 多模块单元测试 项目示例
时间: 2023-07-25 13:42:21 浏览: 332
以下是一个简单的 Spring Boot 多模块项目示例,包含父模块和两个子模块,分别是 `user-service` 和 `order-service`:
父模块 `multi-module` 的 pom.xml 文件:
```xml
<groupId>com.example</groupId>
<artifactId>multi-module</artifactId>
<version>1.0.0</version>
<packaging>pom</packaging>
<modules>
<module>user-service</module>
<module>order-service</module>
</modules>
```
子模块 `user-service` 的 pom.xml 文件:
```xml
<parent>
<groupId>com.example</groupId>
<artifactId>multi-module</artifactId>
<version>1.0.0</version>
</parent>
<groupId>com.example</groupId>
<artifactId>user-service</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<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>
```
子模块 `order-service` 的 pom.xml 文件:
```xml
<parent>
<groupId>com.example</groupId>
<artifactId>multi-module</artifactId>
<version>1.0.0</version>
</parent>
<groupId>com.example</groupId>
<artifactId>order-service</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<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>
```
在 `user-service` 和 `order-service` 子模块中都添加了 `spring-boot-starter-test` 依赖,用于进行单元测试。
在 `user-service` 子模块中编写一个简单的测试类 `UserControllerTest`,测试 `UserController` 中的方法:
```java
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {
@Autowired
private UserController userController;
@Test
public void testGetUserById() {
User user = userController.getUserById(1L);
assertNotNull(user);
assertEquals("Tom", user.getName());
}
}
```
在 `order-service` 子模块中也可以类似地编写测试类。
在父模块 `multi-module` 中,可以通过以下命令运行所有子模块的单元测试:
```
mvn clean test
```
通过以上示例,可以了解如何在 Spring Boot 多模块项目中进行单元测试。
阅读全文
相关推荐

















