0


Spring Boot单元测试

在Spring Boot中进行单元测试通常使用JUnit和Spring Boot Test框架。下面是一个简单的示例来说明如何编写和运行单元测试:

假设你有一个Spring Boot应用程序,其中包含一个服务类UserService,你想要对其中的一个方法进行单元测试。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

@Autowired
private UserRepository userRepository;

public boolean isUserActive(String username) {
    User user = userRepository.findByUsername(username);
    return user != null && user.isActive();
}

}

现在,我们来编写对UserService的isUserActive方法进行单元测试的测试用例。

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;

import static org.junit.jupiter.api.Assertions.;
import static org.mockito.Mockito.
;

@SpringBootTest
public class UserServiceTest {

@Autowired
private UserService userService;

@MockBean
private UserRepository userRepository;

@Test
public void testIsUserActive() {
    // 模拟 UserRepository 的行为
    when(userRepository.findByUsername("testUser")).thenReturn(new User("testUser", true));
    when(userRepository.findByUsername("inactiveUser")).thenReturn(new User("inactiveUser", false));
    when(userRepository.findByUsername("nonExistingUser")).thenReturn(null);

    // 测试用户存在且激活的情况
    assertTrue(userService.isUserActive("testUser"));

    // 测试用户存在但未激活的情况
    assertFalse(userService.isUserActive("inactiveUser"));

    // 测试用户不存在的情况
    assertFalse(userService.isUserActive("nonExistingUser"));
}

}

在这个测试用例中,我们使用了@SpringBootTest注解来指示这是一个Spring Boot测试,并自动配置了应用程序的上下文。使用@MockBean注解来模拟UserRepository的行为,使得我们可以在测试中控制它的返回值。然后我们对UserService的isUserActive方法进行了三种情况的测试:用户存在且激活、用户存在但未激活、用户不存在。

通过这种方式,我们可以很容易地编写和运行Spring Boot应用程序的单元测试,以确保代码的正确性和稳定性。

标签: sql spring boot

本文转载自: https://blog.csdn.net/m0_47192788/article/details/137105110
版权归原作者 m0_47192788 所有, 如有侵权,请联系我们删除。

“Spring Boot单元测试”的评论:

还没有评论