springboot怎么写单元测试

Java Spring Boot提供了一个非常方便的测试框架,可以轻松地编写单元测试。下面是一个详细的例子:

假设我们有一个简单的控制器类,用于处理HTTP请求,并返回JSON格式的响应:

@RestController
public class UserController {
    @Autowired
    private UserService userService;

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

我们的UserService类也非常简单,只是从一个内存列表中获取用户对象:

@Service
public class UserService {
    private List<User> userList = Arrays.asList(
            new User(1L, "Alice"),
            new User(2L, "Bob"),
            new User(3L, "Charlie")
    );

    public User getUserById(Long id) {
        return userList.stream()
                .filter(user -> user.getId().equals(id))
                .findFirst()
                .orElse(null);
    }
}

现在我们想编写一个单元测试来测试这个控制器的行为。我们可以使用Spring Boot提供的MockMvc类来模拟HTTP请求和响应,并使用Mockito来模拟UserService。

@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserService userService;

    @Test
    public void testGetUserById() throws Exception {
        // 模拟UserService返回一个用户对象
        User user = new User(1L, "Alice");
        Mockito.when(userService.getUserById(1L)).thenReturn(user);

        // 发送HTTP GET请求
        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/users/1"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8))
                .andReturn();

        // 解析响应JSON字符串
        ObjectMapper objectMapper = new ObjectMapper();
        User responseUser = objectMapper.readValue(result.getResponse().getContentAsString(), User.class);

        // 验证返回的用户对象是否正确
        Assert.assertEquals(user.getId(), responseUser.getId());
        Assert.assertEquals(user.getName(), responseUser.getName());
    }
}

在这个测试中,我们使用了@RunWith注解来指定测试运行器,@WebMvcTest注解来指定要测试的控制器类,@Autowired注解来注入MockMvc实例,@MockBean注解来注入UserService的模拟对象。

在testGetUserById方法中,我们使用Mockito.when方法来模拟UserService的行为,然后使用MockMvc.perform方法来发送HTTP GET请求,并使用MockMvcResultMatchers来验证响应的状态码和内容类型。最后,我们使用ObjectMapper来解析响应JSON字符串,并验证返回的用户对象是否正确。

总之,Java Spring Boot提供了非常方便的测试框架,可以帮助我们编写高质量的单元测试。

经验分享 程序员 微信小程序 职场和发展