springboot单元测试案例

本文介绍了如何在SpringBoot项目中使用JUnit5进行单元测试,包括在pom.xml中添加依赖,如SpringBootStarterTest并排除Junit4,以及如何使用Mockito模拟Service和Controller类进行复杂测试,如UserController的getUser()方法测试。
摘要由CSDN通过智能技术生成

首先,你需要在pom.xmlbuild.gradle中添加必要的依赖:

如果你使用的是Maven,那么在pom.xml中添加:

<dependencies>
    <!-- Junit 5 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <!-- Exclude the old Junit 4 -->
            <exclusion>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

假设我们要对一个服务类进行单元测试,服务类如下:

@Service
public class MyService {

    public String greet(String name) {
        return "Hello, " + name;
    }
}

对应的单元测试如下:

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import static org.junit.jupiter.api.Assertions.assertEquals;

@SpringBootTest
public class MyServiceTest {

    @Autowired
    private MyService myService;

    @Test
    public void testGreet() {
        String result = myService.greet("John");
        assertEquals("Hello, John", result);
    }
}

在这个测试中:

  • @SpringBootTest是一个标记测试类,该类应在Spring Boot上下文中运行的注解。
  • @Autowired注解用于注入MyService对象。
  • @Test注解标记实际的测试方法testGreet()。在该方法中,我们调用服务方法greet(),并使用JUnit assertEquals()来验证结果是否符合预期。
  • 注意使用的JUnit版本是JUnit 5,前面在pom.xml中排除了Junit 4的依赖。

在Spring Boot应用中,通常我们还会使用Mock对象进行更复杂的单元测试,例如测试Controller或者涉及到数据库的操作。

UserController的示例:

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/users/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.getUserById(id);
    }
}

UserService的示例:

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public User getUserById(Long id) {
        return userRepository.findById(id).orElseThrow(() -> new UserNotFoundException("User not found"));
    }
}

假设需要测试UserController的getUser()方法。通常我们不会想要在单元测试中连接到实际的数据库,因此我们可以使用Mockito来模拟UserService类。

下面是如何进行的测试代码:

import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserService userService;

    @Test
    public void testGetUser() throws Exception {
        User user = new User();
        user.setId(1L);
        user.setName("John");

        Mockito.when(userService.getUserById(1L)).thenReturn(user);

        mockMvc.perform(get("/users/1"))
                .andExpect(status().isOk())
                .andExpect(content().json("{\"id\":1,\"name\":\"John\"}"));
    }
}

在这个测试中:

  • @SpringBootTest@AutoConfigureMockMvc注解用于设置Spring Boot上下文和MockMvc。
  • 利用@MockBean我们模拟了UserService类。当getUserById()方法被调用并接收到1L作为参数时,它会返回一个预先设置的User对象。
  • 最后,用mockMvc.perform(get("/users/1"))来模拟一个HTTP请求,并用andExpect()检查返回的HTTP状态和返回的JSON内容。

这是一个在Spring Boot项目中进行单元测试的基本例子。正如你看到的,Spring Boot配合JUnit和Mockito,能非常方便的进行各种复杂的单元测试。

  • 17
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,以下是一个简单的 Spring Boot 单元测试 controller 的示例代码: 假设我们有一个 UserController 类,其中有一个方法 getUserById,用于根据用户 ID 查询用户信息。我们可以编写一个 UserControllerTest 类,来测试这个方法。 UserController 类代码: ```java @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @GetMapping("/{id}") public User getUserById(@PathVariable Long id) { return userService.getUserById(id); } } ``` UserControllerTest 类代码: ```java @RunWith(SpringRunner.class) @WebMvcTest(UserController.class) public class UserControllerTest { @Autowired private MockMvc mockMvc; @MockBean private UserService userService; @Test public void testGetUserById() throws Exception { // 准备测试数据 User user = new User(); user.setId(1L); user.setUsername("test"); user.setPassword("test123"); user.setAge(18); // 设置 userService 的行为 when(userService.getUserById(1L)).thenReturn(user); // 发送 GET 请求 mockMvc.perform(get("/users/1")) // 验证返回状态码 .andExpect(status().isOk()) // 验证返回数据 .andExpect(jsonPath("$.id").value(user.getId())) .andExpect(jsonPath("$.username").value(user.getUsername())) .andExpect(jsonPath("$.password").value(user.getPassword())) .andExpect(jsonPath("$.age").value(user.getAge())); } } ``` 该测试类使用了 @RunWith(SpringRunner.class) 注解来指定使用 SpringRunner 来运行测试,并使用了 @WebMvcTest(UserController.class) 注解来指定需要测试的 controller 类。 在测试方法中,我们首先使用 Mockito 的 @MockBean 注解来创建一个 UserService 的 mock 对象,然后通过 when(userService.getUserById(1L)).thenReturn(user) 来设置 mock 对象的行为。 接下来,我们使用 MockMvc 发送 GET 请求,并通过 andExpect() 方法来验证返回状态码和返回数据。在这个例子中,我们使用了 jsonPath() 方法来验证返回的 JSON 数据。 需要注意的是,该测试类并没有启动整个 Spring Boot 应用程序,而是只启动了一个 mock servlet 容器,这样测试效率会更高。 希望这个示例能够帮到你。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哎 你看

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值