Springboot中JUNIT5单元测试+Mockito详解
warning:
这篇文章距离上次修改已过426天,其中的内容可能已经有所变动。
在Spring Boot项目中使用JUnit 5和Mockito进行单元测试可以帮助我们模拟外部依赖,避免对外部系统的依赖,从而使得测试更加快速和可靠。以下是一个简单的例子:
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.mockito.Mockito.when;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ExtendWith(MockitoExtension.class)
@SpringBootTest
public class MyServiceTest {
@Autowired
private MyService myService;
@Mock
private MyDependency myDependency;
@Test
public void testMyService() {
when(myDependency.getResult()).thenReturn("Mocked Result");
assertEquals("Mocked Result", myService.getResultFromDependency());
}
}在这个例子中,@ExtendWith(MockitoExtension.class) 告诉JUnit 5使用Mockito来模拟对象。@SpringBootTest 告诉Spring Boot加载应用程序上下文。@Mock 注解标记的字段 myDependency 被模拟,when(myDependency.getResult()).thenReturn("Mocked Result") 设定了模拟方法的行为,使得 myService.getResultFromDependency() 返回"Mocked Result"。这样就可以对 MyService 进行测试,而不需要实际地去调用 MyDependency 的实现。
评论已关闭