首先,你需要在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,能非常方便的进行各种复杂的单元测试。

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐