温馨提示×

spring boot junit与Mockito配合

小樊
87
2024-07-21 15:02:08
栏目: 编程语言

在Spring Boot项目中,通常会使用JUnit和Mockito来进行单元测试和mock对象的操作。以下是如何在Spring Boot项目中使用JUnit和Mockito进行配合的一般步骤:

  1. 首先,在pom.xml文件中添加JUnit和Mockito的依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>3.10.0</version>
    <scope>test</scope>
</dependency>
  1. 创建一个测试类,并使用@Test注解标记测试方法。在测试方法中,使用Mockito的Mockito.mock()方法创建一个mock对象,并设置mock对象的行为。
import static org.mockito.Mockito.*;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyServiceTest {

    @Mock
    private MyRepository myRepository;

    @InjectMocks
    private MyService myService;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testGetById() {
        when(myRepository.findById(1L)).thenReturn(new MyEntity(1L, "test"));
        
        MyEntity result = myService.getById(1L);
        
        assertThat(result.getName()).isEqualTo("test");
    }
}
  1. 使用@InjectMocks注解将mock对象注入到被测试的类中,这样就可以在测试方法中使用mock对象来模拟依赖的行为。

  2. 在测试方法中,使用Mockito的when()方法和thenReturn()方法来设置mock对象的行为,然后调用被测试的方法,并断言结果是否符合预期。

通过以上步骤,我们可以在Spring Boot项目中使用JUnit和Mockito进行配合,编写单元测试并测试项目中的业务逻辑。

0